Is it possible to count integers in an array that match a criteria (e.g. less than n
) without a foreach loop?
$arr = range(0,100); // not always consistent 0,1,2,3...100. Could be 1,1,3,5,25,6,10,100.
$n = 20;
echo countLessThan($n,$arr); // can this work without a loop?
echo countLessLoop($n,$arr); // works, with the help of a loop
// can you make this work without a loop?
function countLessThan($n,$arr) {
$count = ?; // number of items in $arr below $n
return $count;
}
// this works, but with a loop
function countLessLoop($n,$arr) {
$count = 0;
foreach($arr as $v) {
if ($v < $n) $count++;
}
return $count;
}
One generic method can be use of
array_filter
function which creates an array of elements meeting some criterion (given as a function name)for example to count number of elements in array bigger then 3 one can run
which prints
But obviously - without any restrictions on criterion and/or array - any solution will use a loop "under the hood" (and provided answer also loops, but simply using language predefined functions).