64

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

0

5 Answers 5

120

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 !== ""); });
2
  • empty() is most appropriately used when checking for two possibilities: 1. a variable is not declared or 2. a variable contains a falsey value. In this case, there is no reason to check if $x is undeclared because it is guaranteed to be declared by the anonymous function. Instead a simple return $x; will suffice -- that is, if not using the most simple array_filter($array) technique. Jan 31, 2022 at 7:01
  • Indeed, using empty() here makes little sense because an array of values will be passed anyway, but the explicit way abstracts better to other cases of array filtering and counting.
    – moeffju
    Jul 11, 2022 at 12:58
30
count(array_filter($name));
2
  • 18
    Note that this does not just return empty elements but every element that’s value is equal to false (i.e. "", null, 0, false, "0").
    – Gumbo
    Dec 12, 2010 at 17:35
  • 1
    I'd better offset Gumbo's warning and make sure that researchers (and voters) are aware that moeffju's answer will perform identically to this one because empty() performs with the same greedy rules as array_filter() without a callback. Jan 31, 2022 at 7:03
5

Possible Solution: First you need to remove empty/null, false and zero values from an array and then count remaining values of an array

If you no need to remove zero values from an array, but remove null and false values

count(array_filter($arrayName, 'strlen'));
//"strlen" use as second parameter if you no need to remove zero '0' values

if you need to remove zero, null and false values from an array

count(array_filter($arrayName));
1

Here's a simple calculation function:

function non_empty(array $a) {
    return array_sum(array_map(function($b) {return empty($b) ? 0 : 1;}, $a));
}

This will preserve array indexes if your form handling function needs them, like when you're associating the third input on name to the third value of another input set, and there are empty inputs in between them.

0

The easyest aproach is to use count() and array_filter() functions (eventually with an additional callback within array_filter() when we need type compatibility checking, but when the result of default empty() function is enough for us we don't need it).

However, we can also achieve that by using the array_reduce() function, and this approach is slightly more optimal in terms of computational complexity:

$initial = 0;
$count = array_reduce($arr, function($carry, $item) {
    $carry += empty($item) ? 0 : 1;
    return $carry;
}, $initial);

The $count variable counts all non-empty items in the array $arr.

Note that, the condition can be changed if someone wishes, e.g. instead of empty($item) we can use a stronger condition $item === '', etc.

When the array $arr is empty, $initial is returned.

5
  • $carry += !empty($item); also works because the boolean return will be converted to a 1 or a 0 during addition. However, I would never call empty() when I know a variable is guaranteed to exist. In other words, you could use $carry += (bool)$item; Jan 31, 2022 at 7:22
  • Thanks for your comment, @mickmackusa. Of course, your examples are correct, but I prefer to use the ternary (?:) operator instead of implicitly casting on an integer. I was curious that you prefer to cast a variable to be boolean than use empty() on that variable when guaranteed. Why? Does it have to do with performance? Jan 31, 2022 at 15:27
  • 1
    When I can eliminate iterated function calls I often do so. Because for general-use we don't know how many iterations there will be, there may be only 5 or there could be 100,000. Ternary is fine too. $carry += $item ? 1 : 0; Jan 31, 2022 at 20:53
  • Thanks for the clarification, @mickmackusa. I look at these functions as an O(1) operation. But I agree that executing a function, even such a simple and built-in one, may involve additional jumps in memory to the definition of the function. Jan 31, 2022 at 22:50
  • BTW @mickmackusa: Of course, the answer's code example loop is the O(n) type independent of the empty() function usage. Jan 31, 2022 at 22:57

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.