Counting Array Occurrences: Moving Beyond Nested Loops
When you need to tally how many times each item appears in an array, the goal is usually a clean mapping of unique values to their counts. The snippet provided attempts this using a nested loop structure and manual state management, but it suffers from logical flaws that prevent it from producing the expected result. Specifically, the code tries to mutate an associative-like structure ($previous) while iterating over it, and it relies on undefined variables like $counter.
In PHP, there is a much more robust way to handle this: array_count_values. This built-in function returns an associative array where keys are the values from the input array and values are their counts. It handles duplicates correctly without requiring manual state tracking. If you prefer building this logic manuallyâfor instance, to understand the underlying mechanics or to use it in a custom data structureâyou can achieve the same result efficiently with array_reduce or a simple associative array approach.
The Problem with Nested Loops
The provided code snippet initializes $previous as an empty array but attempts to treat it as both a search container and a storage bucket simultaneously. Inside the outer loop, you iterate through every element of the input array. For each element, you then iterate through the entire $previous array to check for existence. This creates an $O(n^2)$ time complexity scenario, which becomes prohibitively slow as data grows.
Furthermore, the logic inside the else block attempts to increment a counter and unset the last element of the $previous array. This is fundamentally flawed because:
- The variable
$counteris never initialized before the loop starts. - Unsetting elements in the middle of an iteration or based on dynamic indices while looping can lead to skipped checks or infinite loops depending on how PHP handles the array keys.
- The condition
if($current != $previous[count($previous)][0])assumes$previousis a multi-dimensional array where the first index is always the value, but since it's initially empty, accessing$previous[0]immediately causes an undefined index notice or logic error on the first pass.
A Simpler Manual Approach
If you want to replicate the logic without using array_count_values, the pattern should be straightforward: iterate once, check if the key exists in your result map, and either initialize it or increment its count.
Here is a clean implementation that produces the expected output:
<?php
$array = [12, 43, 66, 21, 56, 43, 43, 78, 78, 100, 43, 43, 43, 21];
$occurrences = [];
foreach ($array as $value) {
if (array_key_exists($value, $occurrences)) {
$occurrences[$value]++;
} else {
$occurrences[$value] = 1;
}
}
// Or more concisely using the post-increment assignment:
/*
$occurrences = [];
foreach ($array as $value) {
$occurrences[$value] = ($occurrences[$value] ?? 0) + 1;
}
*/
var_dump($occurrences);
// Output: array(7) { ["12"]=> int(1), ["43"]=> int(6), ... }
This approach runs in $O(n)$ time because each element is processed exactly once, and associative array lookups are constant time on average. The resulting structure is a standard associative array where keys are the unique values and values are the counts. You can then convert this to a list of arrays if you specifically need the format [[value, count], ...].
Leveraging Built-in Functions
For production code, relying on array_count_values is best practice unless you have specific constraints preventing its use. It abstracts away the iteration logic and potential edge cases regarding empty arrays or non-integer keys.
$counted = array_count_values($array);
// To format it as a list of arrays:
$formatted = [];
foreach ($counted as $value => $count) {
$formatted[] = [$value, $count];
}
Integrating with Laravel Ecosystem
If you are working within the Laravel framework, this pattern is frequently needed when processing collections or querying databases. While array_count_values works for simple arrays, Laravel Collections offer a fluent interface for this task. You can use the groupBy method followed by count, which feels more idiomatic to Laravel developers:
use Illuminate\Support\Collection;
$collection = collect($array)->groupBy(function ($item) {
return $item;
});
$counted = $collection->mapWithKeys(function ($items, $key) {
return [$key => count($items)];
})->toArray();
This approach is particularly useful when you are already manipulating data pipelines, as it keeps the code readable and consistent with Laravel's philosophy of chaining operations. While array_count_values remains the most performant option for raw arrays, understanding how to map this logic into your existing stack ensures you can tackle duplicate counting tasks regardless of whether you are writing core scripts or building application features.
