How to count non-empty entries in a PHP array?

You can use array_filter to only keep the values that are “truthy” in the array, like this:

array_filter($array);

If you explicitly want only non-empty, or if your filter function is more complex:

array_filter($array, function($x) { return !empty($x); });
# function(){} only works in in php >5.3, otherwise use create_function

So, to count only non-empty items, the same way as if you called empty(item) on each of them:

count(array_filter($array, function($x) { return !empty($x); }));

However, as empty() is only a shorthand for ‘variable is set and the value is truthy’, you don’t really gain anything from that, because if your array contains values such as FALSE or "0", those would count as empty as well, same as with the plain call to array_filter.

The better way is to be explicit about what you want to count, e.g. if you want to exclude empty strings only, then use:

array_filter($array, function($x) { return ($x !== ""); });

Leave a Comment