如何在PHP中获取数组中非空元素的数量。

9
我希望能够在数组中仅获取非空值的数量,如果我使用count()sizeof,它将获取所有索引,包括空值。在我的情况下,我有一个像这样的数组:Array ( [0] => )count1,但我想要获得非空的数量,在这种情况下应该是0,我该如何操作,请帮忙。

仅删除NULL''(空字符串)和FALSE是否也可以删除(基本上是PHP中的FALSE)? - hakre
5个回答

21

只需使用没有回调函数的array_filter()函数即可。

print_r(array_filter($entry));

15
$count = count(array_filter($array));

array_filter会移除任何被计算为false的条目,例如null、数字0和空字符串。如果你只想移除null,需要使用:

$count = count(array_filter($array,create_function('$a','return $a !== null;')));

1

类似于...

$count=0;
foreach ($array as $k => $v)
{
    if (!empty($v))
    {
        $count++;
    }
}

应该可以解决问题。 您还可以像这样将其包装在函数中:

function countArray($array)
{
$count=0;
foreach ($array as $k => $v)
{
    if (!empty($v))
    {
        $count++;
    }
}
return $count;

}

echo countArray($array);

你应该使用isset而不是empty。empty会将false和0返回为true。 - Kevin Smeeks

0
// contact array
$contact_array = $_POST['arr'];

//remove empty values from array
$result_contact_array = array_filter($contact_array);

0

一个选项是

echo "Count is ".count(array_filter($array_with_nulls, 'strlen'));

如果不计算空值和 null 值,你可以这样做

echo "Count is ".count(array_filter($array_with_nulls));

在这个博客中,您可以看到更多的信息。

http://briancray.com/2009/04/25/remove-null-values-php-arrays/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接