In programming, it can be useful to count the number of times duplicate elements appear in an array. To do this, we need to create an efficient solution that accurately captures the desired data.
Understanding the Original Code
The provided code attempts to achieve this by iterating through the array multiple times and maintaining a $previous array to store unique elements and their occurrences. However, it has several issues:
An Efficient Solution
A simpler and more efficient solution is to use the built-in array_count_values function, which counts the occurrences of each unique element in an array. This function returns an associative array where the keys are the unique elements and the values are their respective counts.
$array = [12, 43, 66, 21, 56, 43, 43, 78, 78, 100, 43, 43, 43, 21]; $vals = array_count_values($array);
This code snippet stores the count of each unique element in the $vals array. The output is:
No. of NON Duplicate Items: 7 Array ( [12] => 1 [43] => 6 [66] => 1 [21] => 2 [56] => 1 [78] => 2 [100] => 1 )
This result provides both the number of unique items (7) and the counts for each unique element, which is the desired outcome.
The above is the detailed content of How Can I Efficiently Count Duplicate Occurrences in an Array?. For more information, please follow other related articles on the PHP Chinese website!