In PHP, you can use the array_count_values() function to deduplicate an array and retain the number of repeated elements. This function returns an associative array where the keys are the elements in the original array and the values are the number of times those elements occur.
PHP array deduplication and retain the number of duplicate elements
In PHP, we often encounter the need to deduplicate arrays , but it is also necessary to retain the number of occurrences of repeated elements. We can use the array_count_values()
function to achieve this functionality.
Usage:
array_count_values($array)
will return a new associative array, where the key is the element in the original array and the value is The number of times these elements appear. For example:
$array = [1, 2, 3, 4, 5, 1, 2, 3]; $counts = array_count_values($array); print_r($counts);
Output:
[1] => 2 [2] => 2 [3] => 2 [4] => 1 [5] => 1
Practical case:
The following is a practical case that demonstrates how to use array_count_values()
Function to deduplicate the array and keep the number of duplicate elements:
// 创建一个包含重复元素的数组 $array = ['apple', 'orange', 'apple', 'banana', 'orange', 'cherry']; // 使用 array_count_values() 去重并统计重复元素出现的次数 $counts = array_count_values($array); // 遍历关联数组,打印水果名称和出现的次数 foreach ($counts as $fruit => $count) { echo "$fruit出现了 $count 次\n"; }
Output:
apple出现了 2 次 orange出现了 2 次 banana出现了 1 次 cherry出现了 1 次
Through the array_count_values()
function, we can easily deduplicate the array and keep it The number of times the element is repeated. This is very useful in scenarios such as data statistics and analysis.
The above is the detailed content of PHP array deduplication and retain the number of duplicate elements. For more information, please follow other related articles on the PHP Chinese website!