PHP
Count Frequency of All Values in an Array
Discover how to efficiently count the occurrences of each unique value within a simple or indexed array in PHP using `array_count_values()`.
<?php
$fruits = ['apple', 'banana', 'orange', 'apple', 'grape', 'banana', 'apple'];
$counts = array_count_values($fruits);
/*
$counts will be:
[
'apple' => 3,
'banana' => 2,
'orange' => 1,
'grape' => 1
]
*/
$numbers = [1, 5, 2, 5, 1, 1, 3, 2];
$numberCounts = array_count_values($numbers);
/*
$numberCounts will be:
[
1 => 3,
5 => 2,
2 => 2,
3 => 1
]
*/
?>
How it works: The `array_count_values()` function counts all the values in an array and returns an associative array where the keys are the unique values from the original array and the values are their respective frequencies (counts). This is particularly useful for statistical analysis or data summaries.