4

How can I exclude null values from a count on an array? since count always includes null values in the counting!

2
  • PHP nulls are not the same as SQL nulls. You'll have to roll your own my_count() function to account for this. Commented Mar 20, 2012 at 14:54
  • 1
    possible duplicate of how to count non-empty entries in php array? Commented Mar 20, 2012 at 14:54

4 Answers 4

4
count(array_filter($array, function($x) {return !is_null($x); })
Sign up to request clarification or add additional context in comments.

3 Comments

Elegant solution, but this constructs a temporary list in memory. Still waiting for itertools.ifilter ;)
@phihag Thanks. Yes, if you're on a limited shared memory host or have a very large array to go through, the above implementation may not be the most efficient. Edit: Thanks for editing the code for fix.
Or even count($array) - count(array_filter($array, 'is_null')). Better to use built-in than to declare your own anonymous function :-)
4
function count_nonnull($a) {
    $total = 0;
    foreach ($a as $elt) {
        if (!is_null($elt)) {
            $total++;
        }
    }
    return $total;
}

1 Comment

I'd love to see some braces in there.
3

Try using a foreach loop.

foreach($array as $index=>$value) {
    if($value === null) unset($array[$index]);
}
echo count($array);

Or if you don't want to modify the array:

function myCount($arr)  {
    $count = 0;
    foreach($arr as $index=>$value) {
        if($value !== null) $count++;
    }
    return $count;    
}

echo myCount($array);

5 Comments

Still in instead of as. And you don't need $index=> in the second (arguably preferable) version.
@phihag oops, that was accidental... Fixed that.
I believe that the 'foreach' statement in the function should read: foreach($arr as $index=>$value). Sadly SO doesn't allow others to submit edits which are less than 6 characters or I'd have corrected it myself ;-)
@ChayaCooper I am not sure how that is any different from the current answer.
oh. I see. I will fix @ChayaCooper
1

// easiest way
echo count(array_filter($array)); instructions

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.