Home >Backend Development >PHP Tutorial >How to Detect and Count Duplicate Values in a PHP Array?
Detect and Count Duplicate Values in an Array
When working with arrays in PHP, it can be useful to identify and count duplicate values. Here's a common programming task involving this:
Problem:
Given a one-dimensional array of elements, determine the presence of duplicate values and count their occurrences. For instance, with the following array:
$array = ['apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi'];
An expected output would be:
apple (2) orange pear (2) banana kiwi (3)
Solution:
To approach this problem effectively, you can utilize the built-in array_count_values() function in PHP. Here's how:
$array = ['apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi']; $counts = array_count_values($array); foreach ($counts as $key => $value) { echo "$key ($value)\n"; }
The array_count_values() function generates a new array where each key represents a unique element from the original array, and the associated value indicates the number of times that element appears. By iterating through this new array, you can identify and count the duplicate values in your initial array.
The above is the detailed content of How to Detect and Count Duplicate Values in a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!