PHP Program to Find Frequency of Elements
array_count_values() to find the frequency of elements in an array, like $freq = array_count_values($array); which returns an associative array with elements as keys and their counts as values.Examples
How to Think About It
Algorithm
Code
<?php $array = [1, 2, 2, 3, 3, 3]; $frequency = array_count_values($array); print_r($frequency); ?>
Dry Run
Let's trace the array [1, 2, 2, 3, 3, 3] through the code.
Input array
The array is [1, 2, 2, 3, 3, 3].
Count frequencies
array_count_values counts each element's occurrences.
Result
The frequency array is [1 => 1, 2 => 2, 3 => 3].
| Element | Count |
|---|---|
| 1 | 1 |
| 2 | 2 |
| 3 | 3 |
Why This Works
Step 1: Using array_count_values
The function array_count_values() takes an array and returns an associative array where keys are the unique elements and values are their counts.
Step 2: Counting elements
It loops internally through the array once, counting how many times each element appears.
Step 3: Output format
The output is easy to use because it directly maps each element to its frequency.
Alternative Approaches
<?php $array = [1, 2, 2, 3, 3, 3]; $freq = []; foreach ($array as $item) { if (isset($freq[$item])) { $freq[$item]++; } else { $freq[$item] = 1; } } print_r($freq); ?>
<?php $array = [1, 2, 2, 3, 3, 3]; $freq = array_reduce($array, function($carry, $item) { $carry[$item] = ($carry[$item] ?? 0) + 1; return $carry; }, []); print_r($freq); ?>
Complexity: O(n) time, O(n) space
Time Complexity
The function loops through the array once, so the time grows linearly with the number of elements.
Space Complexity
It creates a new array to store counts, which can be as large as the number of unique elements.
Which Approach is Fastest?
array_count_values() is the fastest and simplest built-in method compared to manual loops or functional methods.
| Approach | Time | Space | Best For |
|---|---|---|---|
| array_count_values() | O(n) | O(n) | Quick and simple frequency count |
| Manual foreach loop | O(n) | O(n) | Understanding logic, custom processing |
| array_reduce() | O(n) | O(n) | Functional programming style |
array_count_values() for a quick and efficient way to count element frequencies in PHP arrays.