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).
We can use the PHP count() or sizeof() function to get the particular number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that we can initialize with an empty array. If we do not set the value for a variable, it returns 0.
The count() function returns the number of elements in an array.
The count() function is used to count the elements of an array or the properties of an object. Note: For objects, if you have SPL installed, you can hook into count() by implementing interface Countable. The interface has exactly one method, Countable::count(), which returns the return value for the count() function.
The count() and sizeof() both functions are used to count all elements in an array and return 0 for a variable that has been initialized with an empty array. These are the built-in functions of PHP. We can use either count() or sizeof() function to count the total number of elements present in an 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); }));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With