How to count non-empty entries in a PHP array?
PhpArraysCountPhp Problem Overview
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).
Php Solutions
Solution 1 - Php
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); }));
Solution 2 - Php
count(array_filter($name));
Solution 3 - Php
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));
Solution 4 - Php
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.
Solution 5 - Php
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.