In PHP, the array_count_values() function returns an associative array holding the frequency of each value in an input array. It is handy for statistical or data analysis activities since it can swiftly count the number of occurrences of each element in an array. The returned array’s keys correspond to the unique values discovered in the input array, while the values correspond to the number of times each key appears in the input. This function accepts a single array as input and returns an associative array.
What is the syntax of array_count_values() in PHP?
array array_count_values ( array $input )
Parameter | Details |
---|---|
array | Specify the array to count values of – required |
It accepts a single input, which is the array whose values you wish to count. The function returns an associative array with the keys being the unique values of the input array and the values being their frequency.
Example
The following code, for example, will return an associative array containing the count of each value in the input array:
$input = array(1, "hello", 1, "world", "hello");
$counts = array_count_values($input);
print_r($counts);
This would output:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)
The returned array’s keys are the unique values discovered in the input array, and its values are the number of times each key appears in the input.
For more information about the PHP array_count_values() function see the official reference.