views:

816

answers:

4

Say I have an array like this:

$array = array('', '', 'other', '', 'other');

How can I count the number with a given value (in the example blank)?

And do it efficiently? (for about a dozen arrays with hundreds of elements each) This example times out (over 30 sec):

function without($array) {
    $counter = 0;
    for($i = 0, $e = count($array); $i < $e; $i++) {
        if(empty($array[$i])) {
            $counter += 1;
        }
    }
    return $counter;
}

In this case the number of blank elements is 3.

+6  A: 

Just an idea, you could use array_keys($myArray, "") using the optional second parameter which specifies a search-value. Then count the result.

$myArray = array("", "", "other", "", "other");
$length  = count(array_keys($myArray, ""));
Jonathan Sampson
A: 

I dont know if this would be faster but it's something to try:

foreach($array as $value)
{
  if($value === '')
    $counter++;
}
camomileCase
+4  A: 

How about using array_count _values to get an array with everything counted for you?

Cellfish
A: 

You could also try array_reduce, with a function which would just count the value you are interested in. eg

function is_empty( $v, $w )
{ return empty( $w ) ? ($v + 1) : $v; }

array_reduce( $array, 'is_empty', 0 );

Some benchmarking might tell you if this is faster than array_count_values()

Steve