Damon Damon - 2 months ago 10
PHP Question

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

Consider:

[name] => Array ( [1] => name#1
[2] => name#2
[3] => name#3
[4] => name#4
[5] =>
[6] =>
[7] =>
[8] =>
[9] =>
)


$name = $_POST['name']


I want the result to be
4
.

count ($name) = 9
count (isset($name)) = 1
count (!empty($name)) = 1


I would think that last one would accomplish what I need, but it is not (the empty entries are from unfilled inputs on the form).

Answer

You can use array_filter to only keep the values that are non-empty in the array, like this:

array_filter($array);

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:

count(array_filter($array));
Comments