计算具有给定值的数组中的值的数量

时间:2009-08-23 02:36:47

标签: php arrays count

说我有这样的数组:

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

如何计算具有给定值的数字(在示例空白中)?

并且有效地做到了吗? (对于大约12个阵列,每个阵列有数百个元素) 此示例超时(超过30秒):

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

在这种情况下,空白元素的数量为3。

8 个答案:

答案 0 :(得分:34)

如何使用array_count _values获取包含所有内容的数组?

答案 1 :(得分:27)

只是一个想法,您可以使用array_keys( $myArray, "" )使用指定搜索值的可选第二个参数。然后计算结果。

$myArray = array( "","","other","","other" );
$length  = count( array_keys( $myArray, "" ));

答案 2 :(得分:6)

我不知道这是否会更快但是要尝试:

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

答案 3 :(得分:3)

你也可以试试array_reduce,其功能只计算你感兴趣的价值。例如

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

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

某些基准测试可能会告诉您这是否比array_count_values()

更快

答案 4 :(得分:2)

我们使用array_filter函数来查找数组中的值数

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

答案 5 :(得分:2)

通常仅用于计算空白。 真的取决于用例和所需的速度。就个人而言,我喜欢一行一事。

与所选择的响应类似但是您仍需要一行来将所需数据提取到另一个变量。

$r = count($x) - count(array_filter($x));

答案 6 :(得分:-2)

function arrayvaluecount($array) {

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

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

        $counter =$counter+1;
        }

    }
return $counter;
}

答案 7 :(得分:-2)

function countarray($array)
{        $count=count($array);         
         return $count;        
}        
$test=$array = array('', '', 'other', '', 'other');        
echo countarray($test);
相关问题