How can I exclude null values from a count on an array? since count always includes null values in the counting!
4 Answers
count(array_filter($array, function($x) {return !is_null($x); })
3 Comments
phihag
Elegant solution, but this constructs a temporary list in memory. Still waiting for
itertools.ifilter ;)PenguinCoder
@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.
TerryE
Or even
count($array) - count(array_filter($array, 'is_null')). Better to use built-in than to declare your own anonymous function :-)function count_nonnull($a) {
$total = 0;
foreach ($a as $elt) {
if (!is_null($elt)) {
$total++;
}
}
return $total;
}
1 Comment
phihag
I'd love to see some braces in there.
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
phihag
Still
in instead of as. And you don't need $index=> in the second (arguably preferable) version.Naftali
@phihag oops, that was accidental... Fixed that.
Chaya Cooper
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 ;-)
Naftali
@ChayaCooper I am not sure how that is any different from the current answer.
Naftali
oh. I see. I will fix @ChayaCooper
my_count()function to account for this.