Number of elements that have at least the reported value

0

I have an array that can be any size, an example below:

Array
(
  [0] => 40631
  [1] => 40626
  [2] => 40622
  [3] => 40633
  [4] => 59632
  [5] => 40630
  [6] => 40623
  [7] => 40627
  [8] => 40628
  [9] => 54828
  [10] => 40623
  [11] => 40630
  [12] => 42623
  [13] => 54318
)

When entering any value, for example the number 50000, I should return the number of values that have at least 50000.

In this example, the function should return: 3

As this array can have N sizes and can receive any value to fetch the array, what form to look for the quantity and with the best performance?

    
asked by anonymous 13.04.2018 / 02:53

2 answers

1

In PHP, you'd better worry about simplicity rather than performance, since the language itself was not designed to be quick, but to simplify some tasks. In this case, just use the array_filter function:

$values = [
  40631,
  40626,
  40622,
  40633,
  59632,
  40630,
  40623,
  40627,
  40628,
  54828,
  40623,
  40630,
  42623,
  54318,
];

$filtered = array_filter($values, function ($value) {
  return $value >= 50000;
});

print_r($filtered);

See working at Repl.it

The result will be:

Array
(
    [4] => 59632
    [9] => 54828
    [13] => 54318
)

To get the quantity, just do:

$quantidade = count($filtered);  // 3
    
13.04.2018 / 03:10
0

As you have to go through the entire array to check its values, I think the best way is to foreach itself:

<?php
$array = array('40631','40626','40622','40633','59632','54828');

$conta = 0;

foreach($array as $item){
   if($item >= 50000) $conta++;
}

echo $conta; // retorna 2

?>

Ideone Test

    
13.04.2018 / 03:09