简体   繁体   中英

Count number of values in array with a given value

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.

如何使用array_count _values来获得一个为您计算一切的数组?

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, "" ));

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

$counter = 0;
foreach($array as $value)
{
  if($value === '')
    $counter++;
}
echo $counter;

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

We use array_filter function to find out number of values in array

$array=array('','','other','','other');
$filled_array=array_filter($array);// will return only filled values
 $count=count($filled_array);
echo $count;// returns array count

Generally for counting blanks only. Really depends on use case and speed needed. Personally I like doing things one one line.

Like the chosen response though But you still need a line to extract the data needed though to another variable.

$r = count($x) - count(array_filter($x));
function arrayvaluecount($array) {

    $counter = 0;
    foreach($array as $val){

        list($v)=$val;
        if($v){

        $counter =$counter+1;
        }

    }
return $counter;
}
function countarray($array)
{        $count=count($array);         
         return $count;        
}        
$test=$array = array('', '', 'other', '', 'other');        
echo countarray($test);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM