Quantity of elements that has at least the reported value

Asked

Viewed 38 times

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 informing any value, for example the number 50000, should return me the amount of values that has at least 50000.

In this example the function must return: 3

As this array can have N sizes and can receive any value to search for the array, how to search for the quantity and with the best performance?

2 answers

1


In PHP, it’s better to worry about simplicity than performance, since the language itself was not created to be fast, but rather to simplify some tasks. In this case, just use the function array_filter:

$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 on Repl.it

The result will be:

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

To get the quantity, just do:

$quantidade = count($filtered);  // 3

0

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

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

$conta = 0;

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

echo $conta; // retorna 2

?>

Testing at Ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.