9

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
  • Only NULL or is '' (empty string) and FALSE okay to remove as well (basically everything FALSE in PHP)? Commented Oct 6, 2011 at 9:47

5 Answers 5

21

simply use array_filter() without callback

print_r(array_filter($entry));
Sign up to request clarification or add additional context in comments.

Comments

15
$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;')));

Comments

1

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

1 Comment

You should be using isset not empty. empty will return true for false and 0
0

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/

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.