Counting Occurrences in PHP Arrays: A Practical Approach
When processing a one-dimensional array in PHP, identifying duplicates and quantifying their frequency is a common requirement for data validation, log analysis, or preparing datasets for aggregation. Consider a scenario where you have a list of fruit names and need to isolate which items appear multiple times while preserving the output order of first appearance.
Given an input array like this:
$array = [
'apple',
'orange',
'pear',
'banana',
'apple',
'pear',
'kiwi',
'kiwi',
'kiwi'
];
The goal is to generate an output where only items with a count greater than one are labeled, while single-occurrence items appear without a suffix. The expected result looks like this:
apple (2)
orange
pear (2)
banana
kiwi (3)
Leveraging Built-in Functions for Frequency Counts
The most straightforward way to solve this in modern PHP (7.4+) is to combine array_count_values() with a few array manipulation steps. This built-in function returns an associative array where keys are the original values and values are their counts. It is highly optimized in C and avoids manual iteration overhead.
Here is how you can implement it:
$counts = array_count_values($array);
// Sort by first occurrence to maintain original order
$sortedCounts = array_udiffu(
$array,
array_keys(array_flip($counts)),
function ($a, $b) use ($counts) {
if (is_numeric($a) && is_numeric($b)) {
return 0;
}
return strcmp($a, $b);
}
);
// Actually, a simpler way to maintain order is to iterate through the original array:
$output = [];
$firstSeen = [];
foreach ($array as $item) {
if (!isset($firstSeen[$item])) {
$firstSeen[$item] = true;
$output[] = $item;
}
}
// Now map counts to the ordered list
$result = [];
foreach ($output as $item) {
if ($counts[$item] > 1) {
$result[] = "{$item} ({$counts[$item]})";
} else {
$result[] = $item;
}
}
print_r($result);
However, there is a cleaner logic flow that avoids intermediate sorting functions entirely. Since we only care about the count of each unique value, we can build an associative array first, then iterate through the original list to ensure order preservation:
$counts = array_count_values($array);
$result = [];
foreach ($array as $item) {
if (isset($result[$item])) {
// Skip duplicates in iteration; we already captured this item earlier
continue;
}
$count = $counts[$item];
if ($count > 1) {
$result[] = "{$item} ({$count})";
} else {
$result[] = $item;
}
// Mark as processed to avoid re-processing
$result[$item] = true;
}
print_r($result);
Why This Approach Works
Using array_count_values() shifts the complexity of counting from your application logic to the PHP engine. This ensures consistent performance even with larger datasets. The critical part of the algorithm is maintaining the original order. By iterating over $array directly and checking if we have already added an item to the result, we guarantee that the output sequence matches the input sequence for unique values.
A common pitfall in this task is sorting the counts by frequency instead of preserving order. While rsort() might seem tempting, it destroys the original appearance order, which often breaks user expectations in UI rendering or log displays. Another mistake is attempting to use nested loops to count manually; this creates O(n²) complexity, which becomes a bottleneck as the array grows.
Handling Edge Cases
If your data contains mixed types (strings and integers), array_count_values() handles them distinctly because PHP treats '1' and 1 as different keys when using numeric indexing, but in an associative context created by this function, they are treated based on their actual value representation. However, if strict string comparison is needed for numeric-looking strings, you may need to cast values explicitly before counting.
Additionally, ensure that the array does not contain resources or objects unless they implement __toString correctly, as array_count_values will attempt to use the string representation of these items. If your data includes complex objects, a manual loop with strict type checking might be safer to avoid unexpected serialization behavior.
For high-scale applications where performance is critical and you need to process millions of rows, consider offloading this logic to Laravel's Eloquent collection methods if working within a framework context. Specifically, groupBy combined with pluck can offer a declarative alternative:
$grouped = collect($array)->groupBy(function ($value) { return $value; });
While this is less performant than the built-in C function for simple arrays, it offers better composability within Laravel pipelines. If you are building a larger application using Laravel, leveraging these collection methods can make your codebase more readable and maintainable, aligning with best practices advocated by experts like those at https://laravelcompany.com.
Ultimately, for simple scripts or CLI tools, array_count_values remains the most efficient and idiomatic solution.
