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

Tom*_*Tom 22 php arrays count

说我有这样的数组:

$array = array('', '', 'other', '', 'other');
Run Code Online (Sandbox Code Playgroud)

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

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

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

在这种情况下,空白元素的数量是3.

Cel*_*ish 36

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


Sam*_*son 28

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

$myArray = array( "","","other","","other" );
$length  = count( array_keys( $myArray, "" ));
Run Code Online (Sandbox Code Playgroud)


cam*_*ase 6

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

$counter = 0;
foreach($array as $value)
{
  if($value === '')
    $counter++;
}
echo $counter;
Run Code Online (Sandbox Code Playgroud)