Is there a way to count integers in an array less than a given point without a foreach loop?

1.7k Views Asked by At

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;
}
3

There are 3 best solutions below

0
On BEST ANSWER

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

function test($x){
 return $x>3; 
}

$data = array( 1,2,3,4,5 );
echo count( array_filter( $data, 'test' ) );

which prints

2

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).

1
On

Sorry not array_map() but array_filter() like this:

$array = array('1', '2', '3', '4', '5', '5');
print_r(array_filter($array,"lessthen"));
function lessthen($val) {
    if ($val<4) {
        return $val;    
    }
    else return NULL;
}

will print:

Array ( [0] => 1 [1] => 2 [2] => 3 )

see more here: http://www.php.net/manual/en/function.array-filter.php

1
On

If sorting of the array is allowed:

(sorting in itself of course is not always cheap and internally involves some loops anyway)

function countLessThan($n,$arr){
  sort($arr);
  return array_search ($n,$arr);
}

otherwise:

function countLessThan($n,$arr){
  $a=array_slice($arr,0);
  sort($a);
  return array_search ($n,$a);
}

But, then again: This only works, if $n is actually a member of $arr, otherwise you will get a wrong result!

For cases, where $n is not part of the array you might want to try a tree-approach by picking a point in the middle of the original array, then checking whether the value is higher or lower than $n and then recursively repeating the process on the remaining half of the array. The recursion is over when the length of an array is 1. The position found is basically the number you are looking for.