Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

count

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

like image 450
Damon Avatar asked Dec 12 '10 17:12

Damon


People also ask

How do I count items in an array PHP?

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.

What is the use of count () function in PHP?

The count() function returns the number of elements in an array.

How do you count objects in PHP?

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.

How do I count the number of numbers in PHP?

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.


1 Answers

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); })); 
like image 69
moeffju Avatar answered Sep 22 '22 20:09

moeffju