PHP array_count_values Function | Count of Values in Array

PHP array_count_values is an inbuilt Function in PHP. It returns an associative array containing 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.

Syntax

array_count_values($array);

Parameters

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.

Return Value

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.

PHP array_count_values Function Diagram

Examples

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
	(
	    [1] => 3
	    [4] => 1
	    [2] => 2
	    [5] => 2
	    [6] => 1
	    [3] => 2
	    [7] => 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
	(
	    [5] => 2
	    [6] => 1
	)
	*/
?>

You can learn more about PHP array_column Function on Concatly.

Conclusion

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 Concatly! Additionally, to learn more about this Function, refer to the Official Documentation of PHP.

Spread the Knowledge

Leave a Reply

Your email address will not be published. Required fields are marked *