PHP
Count the Frequency of All Values in an Array
Quickly count how many times each unique value appears in an array using `array_count_values()`, generating an associative array of frequencies.
<?php
$data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
$frequencies = array_count_values($data);
print_r($frequencies);
// Expected Output: Array ( [apple] => 3 [banana] => 2 [orange] => 1 )
$scores = [85, 90, 75, 90, 85, 95, 85];
$scoreCounts = array_count_values($scores);
print_r($scoreCounts);
// Expected Output: Array ( [85] => 3 [90] => 2 [75] => 1 [95] => 1 )
?>
How it works: The `array_count_values()` function counts all the values of an array and returns an associative array where the keys are the unique values from the input array and the values are their respective frequencies (how many times they appeared). This is highly useful for statistical analysis, tabulation, or getting a quick overview of data distribution.