Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of values in array with a given value

Tags:

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.

like image 941
Tom Avatar asked Aug 23 '09 02:08

Tom


People also ask

How do I count the number of elements in an array PHP?

The count() function returns the number of elements in an array.


1 Answers

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

like image 124
Cellfish Avatar answered Sep 20 '22 18:09

Cellfish