Is the array_count_values() function of PHP only used in one-dimensional arrays? What happens if you pass in a multidimensional array?
In PHP, the array_count_values() function is a very useful function that counts the number of occurrences of each value in an array. The definition of this function is as follows:
array_count_values(array $array): array
The main function of the array_count_values() function is to return an associative array containing all the values in the original array and the number of times each value appears. For example:
$array = array(1, 2, 2, 3, 3, 3, 4);
$result = array_count_values($array);
print_r($result);
The output will be:
Array
(
[1] => 1
[2] => 2
[3] => 3
[4] => 1
)
Strictly speaking, the array_count_values() function is designed for a one-dimensional array, so it will iterate over elements in a one-dimensional array and count the number of times each value appears. If the one-dimensional array is passed in, it can work as expected and return a count result.
However, when we pass in a multidimensional array, array_count_values() will only consider the outermost (first layer) elements of the array, and ignore the array nested in the inner layer. If the array contains multidimensional arrays or other complex data structures, array_count_values() will not recursively process it.
Let's look at an example:
$array = array(
'a' => 1,
'b' => 2,
'c' => array(1, 2),
'd' => 3,
);
$result = array_count_values($array);
print_r($result);
The output will be:
Array
(
[1] => 1
[2] => 1
[3] => 1
)
As you can see, array_count_values() only counts the outermost element, and ignores the array value of the key c . If we want to count all values in a multidimensional array, we must first "flatten", for example, use array_walk_recursive() or handle it through recursion.
If you need to count the number of occurrences of each value in a multidimensional array, you can use a recursive method to flatten the array. Here is an example:
function flattenArray($array) {
$result = [];
array_walk_recursive($array, function($value) use (&$result) {
$result[] = $value;
});
return $result;
}
$array = array(
'a' => 1,
'b' => 2,
'c' => array(1, 2),
'd' => 3,
);
$flattenedArray = flattenArray($array);
$result = array_count_values($flattenedArray);
print_r($result);
The output will be:
Array
(
[1] => 2
[2] => 2
[3] => 1
)
Through recursive mode, we flatten the multi-dimensional array and then use array_count_values() to count. This allows you to count all values in a multidimensional array.
The array_count_values() function itself can only be used for one-dimensional arrays. If a multi-dimensional array is passed in, the function will only count the values of the outermost element, and will not count the values in the nested array. To handle multidimensional arrays, you can flatten them first by recursively or otherwise, and then use array_count_values() to count the number of occurrences of each value.