Home >Backend Development >PHP Tutorial >How to Efficiently Count Duplicate Items in a PHP Array?
Counting Occurrence of Duplicate Items in Array
This task involves counting the occurrences of each duplicate item in an array and creating a new array containing only unique items along with their respective counts.
PHP Implementation
You provided the following PHP code to address this problem:
[PHP code provided in the question]
However, the code seems to contain some anomalies.
Improved Solution
Instead of implementing a custom loop-based approach, you can leverage PHP's built-in functionality with array_count_values():
<code class="php">$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21); $vals = array_count_values($array);</code>
The array_count_values() function counts the occurrences of each unique value in an array and returns an associative array with the unique values as keys and their corresponding counts as values.
Output
The following output is produced:
No. of NON Duplicate Items: 7 Array ( [12] => 1 [43] => 6 [66] => 1 [21] => 2 [56] => 1 [78] => 2 [100] => 1 )
As you can see, the result accurately counts the occurrences of duplicate items in the original array and provides an array of unique items with their respective counts.
The above is the detailed content of How to Efficiently Count Duplicate Items in a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!