n
是否可以在没有 foreach 循环的情况下计算符合条件(例如小于)的数组中的整数?
$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;
}