php - Is there a way to count integers in an array less than a given point without a foreach loop? -
is possible count integers in array match criteria (e.g. less n
) without foreach loop?
$arr = range(0,100); // not consistent 0,1,2,3...100. 1,1,3,5,25,6,10,100. $n = 20; echo countlessthan($n,$arr); // can work without loop? echo countlessloop($n,$arr); // works, of loop // can make work without loop? function countlessthan($n,$arr) { $count = ?; // number of items in $arr below $n return $count; } // works, loop function countlessloop($n,$arr) { $count = 0; foreach($arr $v) { if ($v < $n) $count++; } return $count; }
one generic method can use of array_filter
function creates array of elements meeting criterion (given function name)
for example count number of elements in array bigger 3 1 can run
function test($x){ return $x>3; } $data = array( 1,2,3,4,5 ); echo count( array_filter( $data, 'test' ) );
which prints
2
but - without restrictions on criterion and/or array - solution use loop "under hood" (and provided answer loops, using language predefined functions).
Comments
Post a Comment