PHP array_count_values is an inbuilt Function in PHP. It returns an associative array containing a count of values in an array. In other words, it is used to calculate the frequency of all elements in an array. In this article, we will discuss PHP array_count_values Function. Also, we will go through a few examples demonstrating it’s usage.
The PHP array_count_values Function takes in only one mandatory parameter. This parameter is the array for which we need to calculate the count of values present in it.
The PHP array_count_values Function returns an associative array containing the frequency of all elements. However, it only works when the values are either string or integers. Also, it throws an E_WARNING if the values are not string or integer.
Also, the return array is NOT sorted in any order.
Let’s discuss a few examples to demonstrate the use of PHP array_count_values.
Example 1: Basic Example
For example, consider the following basic example.
<?php $testArray = array('Dog', 'Cat', 'Mouse', 'Dog', 'Cat', 'Lion', 'Tiger', 'Cat'); $countArray = array_count_values($testArray); print_r($countArray); /* Array ( [Dog] => 2 [Cat] => 3 [Mouse] => 1 [Lion] => 1 [Tiger] => 1 ) */ ?>
In the above example, you can observe the output of PHP array_count_values Function. It returns an array with the frequency of elements in the original array. Also, notice that the array is not sorted in any order.
Example 2: Integer Values
Similarly, we can also count frequency of integer elements in an array.
<?php $testArray = array(1,4,2,1,5,6,3,7,3,2,5,1); $countArray = array_count_values($testArray); print_r($countArray); /* Array (  => 3  => 1  => 2  => 2  => 1  => 2  => 1 ) */ ?>
Example 3: Multidimensional Arrays
For instance, suppose we want to find the number of items in a specific key in a multidimensional array. To find the frequency of element in userId key of the array, we can use array_column along with array_count_values Function.
<?php $list = [ ['id' => 1, 'userId' => 5], ['id' => 2, 'userId' => 5], ['id' => 3, 'userId' => 6], ]; print_r(array_count_values(array_column($list, 'userId'))); /* Array (  => 2  => 1 ) */ ?>
You can learn more about PHP array_column Function on Concatly.
In conclusion, we discussed PHP array_count_values Function in PHP. We discussed a few examples illustrating basic usage of the function. You can learn about more Array Functions on
Vishesh is currently working as an Intermediate Software Engineer with Orion Health, New Zealand. He graduated with a Masters in Information Technology from the University of Auckland in 2021. With more than 4 years of work experience, his expertise includes Java, Python, Machine Learning, PHP, Databases, Design and Architecture.