how to get only not null element count in array php

ε祈祈猫儿з 提交于 2020-01-03 13:10:10

问题


i want to get only not null values count in that array , if i use count() or sizeof it will get the null indexes also .

in my case

i have an array like this Array ( [0] => )

the count is 1 . but i want to get the not null count , inthis case it should be 0 , how can i do this , please help............................


回答1:


simply use array_filter() without callback

print_r(array_filter($entry));



回答2:


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

array_filter will remove any entries that evaluate to false, such as null, the number 0 and empty strings. If you want only null to be removed, you need:

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



回答3:


something like...

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

should do the trick. you could also wrap it in a function like:

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

}

echo countArray($array);



回答4:


although i'm not that good with PHP i think you should programatically remove empty elements from the array the link might help




回答5:


One option is

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

If you don't count empty and nulls values you can do this

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

In this blog you can see a little more info

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



来源:https://stackoverflow.com/questions/7672562/how-to-get-only-not-null-element-count-in-array-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!