count
(PHP 4, PHP 5, PHP 7, PHP 8)
count — Count all elements in an array, or something in an object
Description
Counts all elements in an array, or something in an object.
Please see the Array section of the manual for a detailed explanation of how arrays are implemented and used in PHP.
Parameters
An array or Countable object.
If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array.
count() can detect recursion to avoid an infinite loop, but will emit an E_WARNING every time it does (in case the array contains itself more than once) and return a count higher than may be expected.
Return Values
Changelog
| Version | Description |
|---|---|
| 8.0.0 | count() will now throw TypeError on invalid countable types passed to the value parameter. |
| 7.2.0 | count() will now yield a warning on invalid countable types passed to the value parameter. |
Examples
Example #1 count() example
The above example will output:
var_dump ( count ( null ));
var_dump ( count ( false ));
?>
The above example will output:
Output of the above example in PHP 7.2:
Output of the above example in PHP 8:
Example #3 Recursive count() example
See Also
User Contributed Notes 17 notes
[Editor’s note: array at from dot pl had pointed out that count() is a cheap operation; however, there’s still the function call overhead.]
If you are on PHP 7.2+, you need to be aware of «Changelog» and use something like this:
My function returns the number of elements in array for multidimensional arrays subject to depth of array. (Almost COUNT_RECURSIVE, but you can point on which depth you want to plunge).
I actually find the following function more useful when it comes to multidimension arrays when you do not want all levels of the array tree.
$arr [ ‘__been_here’ ] = true ;
to end the debate: count() is the same as empty()
results on my computer:
count : double(0.81396999359131)
empty : double(0.81621310710907)
using isset($test[0]) is a bit slower than empty;
test without adding value to the array in function ****Test: still the same.
A function of one line to find the number of elements that are not arrays, recursively :
Get maxWidth and maxHeight of a two dimensional array.
Note:
1st dimension = Y (height)
2nd dimension = X (width)
e.g. rows and cols in database result arrays
You can not get collect sub array count when there is only one sub array in an array:
$a = array ( array (‘a’,’b’,’c’,’d’));
$b = array ( array (‘a’,’b’,’c’,’d’), array (‘e’,’f’,’g’,’h’));
echo count($a); // 4 NOT 1, expect 1
echo count($b); // 2, expected
For a Non Countable Objects
Warning: count(): Parameter must be an array or an object that implements Countable in example.php on line 159
#Quick fix is to just cast the non-countable object as an array..
As I see in many codes, don’t use count to iterate through array.
Onlyranga says you could declare a variable to store it before the for loop.
I agree with his/her approach, using count in the test should be used ONLY if you have to count the size of the array for each loop.
You can not get collect sub array count when use the key on only one sub array in an array:
$a = array(«a»=>»appple», b»=>array(‘a’=>array(1,2,3),’b’=>array(1,2,3)));
$b = array(«a»=>»appple», «b»=>array(array(‘a’=>array(1,2,3),’b’=>array(1,2,3)), array(1,2,3),’b’=>array(1,2,3)), array(‘a’=>array(1,2,3),’b’=>array(1,2,3))));
echo count($a[‘b’]); // 2 NOT 1, expect 1
echo count($b[‘b’]); // 3, expected
To get the count of the inner array you can do something like:
$inner_count = count($array[0]);
echo ($inner_count);
About 2d arrays, you have many way to count elements :
Criada para contar quantos níveis um array multidimensional possui.
/* Verifica se o ARRAY foi instanciado */
if (is_setVar($matrix))<
/* Verifica se a variável é um ARRAY */
if(is_array($matrix))<
In special situations you might only want to count the first level of the array to figure out how many entries you have, when they have N more key-value-pairs.
If you want to know the sub-array containing the MAX NUMBER of values in a 3 dimensions array, here is a try (maybe not the nicest way, but it works):
$cat_poids_max[‘M’][‘Seniors’][] = 55;
$cat_poids_max[‘M’][‘Seniors’][] = 60;
$cat_poids_max[‘M’][‘Seniors’][] = 67;
$cat_poids_max[‘M’][‘Seniors’][] = 75;
$cat_poids_max[‘M’][‘Seniors’][] = 84;
$cat_poids_max[‘M’][‘Seniors’][] = 90;
$cat_poids_max[‘M’][‘Seniors’][] = 100;
//.
$cat_poids_max[‘F’][‘Juniors’][] = 52;
$cat_poids_max[‘F’][‘Juniors’][] = 65;
$cat_poids_max[‘F’][‘Juniors’][] = 74;
$cat_poids_max[‘F’][‘Juniors’][] = 100;
How can I count the number of element inside an array with value equals a constant? example,
how can I directly know how many «Ben» is inside?
10 Answers 10
You can do this with array_keys and count.
To count a value in a two dimensional array, here is the useful snippet to process and get count of a particular value—
try the array_count_values() function
If you want to count ALL the same occurences inside the array, here’s a function to count them all, and return the results as a multi-dimensional array:
array_count_values only works for integers and strings. If you happen to want counts for float/numeric values (and you are heedless of small variations in precision or representation), this works:
Not the answer you’re looking for? Browse other questions tagged php arrays count or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40224
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
array_count_values
(PHP 4, PHP 5, PHP 7, PHP 8)
array_count_values — Подсчитывает количество всех значений массива
Описание
Список параметров
Массив подсчитываемых значений
Возвращаемые значения
Возвращает ассоциативный массив со значениями array в качестве ключей и их количества в качестве значений.
Ошибки
Генерирует ошибку уровня E_WARNING для каждого элемента, не являющегося строкой ( string ) или целым числом ( int ).
Примеры
Пример #1 Пример использования array_count_values()
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 15 notes
Simple way to find number of items with specific values in multidimensional array:
Based on sergolucky96 suggestion
Simple way to find number of items with specific *boolean* values in multidimensional array:
The case-insensitive version:
I couldn’t find a function for counting the values with case-insensitive matching, so I wrote a quick and dirty solution myself:
Array
(
[J. Karjalainen] => 3
[60] => 2
[j. karjalainen] => 1
[Fastway] => 2
[FASTWAY] => 1
[fastway] => 1
[YUP] => 1
)
Array
(
[J. Karjalainen] => 4
[60] => 2
[Fastway] => 4
[YUP] => 1
)
I don’t know how efficient it is, but it seems to work. Needed this function in one of my scripts and thought I would share it.
I find a very simple solution to count values in multidimentional arrays (example for 2 levels) :
Yet Another case-insensitive version of array_count_values()
Array
(
[j. karjalainen] => 4
[60] => 2
[fastway] => 4
[yup] => 1
)
byron at byronrode dot co dot za, here are some benchmarks.
__array_keys()__
Count:515
Time:0.0869138240814
Memory:33016
__$needle_array[]__
Count:515
Time:0.259949922562
Memory:24792
__$number_of_instances++__
Count:515
Time:0.258481025696
Memory:0
However, when you use an array of strings by calling md5(rand(1, 2000)), the performance boosts become less significant:
__array_count_values()__
Count:499
Time:0.491794109344
Memory:184328
__array_keys()__
Count:499
Time:0.36399102211
Memory:30072
__$needle_array[]__
Count:499
Time:0.568728923798
Memory:22104
__$number_of_instances++__
Count:499
Time:0.574353933334
Memory:0
Results are similar for string->string haystacks with foreach traversal.
PHP array_count_values()
PHP array_count_values() Function
PHP array_count_values() function counts the occurrences of all values in an array and returns an associative array formed by the unique value of input array as keys, and the number of their occurrences in the array as values.
In this tutorial, we will learn the syntax of array_count_values(), and how to use array_count_values() to count the occurrences of values in the array, covering different scenarios based on array type and arguments.
Syntax – array_count_values()
The syntax of PHP array_count_values() function is
| Parameter | Description |
|---|---|
| input | Occurrences of values in this input array are counted. |
Return Value
The array_count_values() function returns an array formed with unique values as keys, and their number of occurrences as values.
Warnings
array_count_values() expects elements of the array have to be either string or integer. So, if an element is neither string nor integer, the function throws a warning.
Example – Count Values
In this example, we will take a array and count the occurrences of values in the array.
PHP Program
Output
The value 41 has occurred two times, a has occurred two times and b has occurred one time in the input array.
There are two observations that we can draw from this output. They are
Example – Count Values in Associative Array
In this example, we will take an associative array with key-value pairs, and call array_count_values(). The keys of associative array are ignored and only the values are considered for counting.
PHP Program
Output
Warning: array_count_values(): Can only count STRING and INTEGER values
array_count_values() can count only STRING and INTEGER values. Warning shall be raised for values, in the array, of any other datatypes.
In the following example, we have an array with one float value, and the rest are strings and integers. call array_count_values() function will throw a warning for the first value, and continues with counting for the string and integer values.
PHP Program
Output
Conclusion
In this PHP Tutorial, we learned how to count occurrences of values in a given array, using PHP Array array_count_values() function.
array_count_values
array_count_values — Подсчитывает количество всех значений массива
Описание
Список параметров
Массив подсчитываемых значений
Возвращаемые значения
Возвращает ассоциативный массив со значениями input в качестве ключей и их количества в качестве значений.
Ошибки
Примеры
Пример #1 Пример использования array_count_values()
Результат выполнения данного примера:
Смотрите также
Коментарии
I find a very simple solution to count values in multidimentional arrays (example for 2 levels) :
Besides, you really ought to be validating each field anyway if you’re taking user input.
I couldn’t find a function for counting the values with case-insensitive matching, so I wrote a quick and dirty solution myself:
Array
(
[J. Karjalainen] => 3
[60] => 2
[j. karjalainen] => 1
[Fastway] => 2
[FASTWAY] => 1
[fastway] => 1
[YUP] => 1
)
Array
(
[J. Karjalainen] => 4
[60] => 2
[Fastway] => 4
[YUP] => 1
)
I don’t know how efficient it is, but it seems to work. Needed this function in one of my scripts and thought I would share it.
Array
(
[j. karjalainen] => 4
[60] => 2
[fastway] => 4
[yup] => 1
)
Yet Another case-insensitive version of array_count_values()
byron at byronrode dot co dot za, here are some benchmarks.
__array_keys()__
Count:515
Time:0.0869138240814
Memory:33016
__$needle_array[]__
Count:515
Time:0.259949922562
Memory:24792
__$number_of_instances++__
Count:515
Time:0.258481025696
Memory:0
However, when you use an array of strings by calling md5(rand(1, 2000)), the performance boosts become less significant:
__array_count_values()__
Count:499
Time:0.491794109344
Memory:184328
__array_keys()__
Count:499
Time:0.36399102211
Memory:30072
__$needle_array[]__
Count:499
Time:0.568728923798
Memory:22104
__$number_of_instances++__
Count:499
Time:0.574353933334
Memory:0
Results are similar for string->string haystacks with foreach traversal.
The case-insensitive version:
In order to apply array_map with callback checking for localised values like city name, country name, you have to provide some sort of comparison array.
Here’s an example of array_count_values for Polish city names. Just switch array_keys / array_values in order to obtain lowercase / uppercase.
Array ( [warsaw] => 3 [wrocław] => 2 [poznań] => 2 [kraków] => 2 [gdańsk] => 2 )
$array = array(1, true, 1, true, false,NULL);
var_dump(array_count_values($array));
//Warning: array_count_values(): Can only count STRING and INTEGER values!
Simple way to find number of items with specific values in multidimensional array:
Based on sergolucky96 suggestion
Simple way to find number of items with specific *boolean* values in multidimensional array:




