Home  >  Article  >  Backend Development  >  PHP array deduplication and retain the number of duplicate elements

PHP array deduplication and retain the number of duplicate elements

WBOY
WBOYOriginal
2024-04-27 11:06:01636browse

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 数组去重并保留重复元素的次数

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn