如果沒有foreach循環,是否可以計算符合條件的數組中的整數(例如,小於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;
}
如果循環中沒有else語句,則無法執行此操作 –
您可以對數組進行排序並查找數字的位置。 – cars10m
數組是排序的嗎?或以任何方式受到限制? –