PHP
Count Frequencies of Array Elements
Quickly count the occurrences of each unique value within a simple or associative array in PHP using the built-in `array_count_values` function for statistical analysis.
<?php
$fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple', 'grape'];
$fruitCounts = array_count_values($fruits);
print_r($fruitCounts);
echo "
";
$ages = [20, 25, 30, 25, 20, 30, 35, 20];
$ageCounts = array_count_values($ages);
print_r($ageCounts);
?>
How it works: This snippet demonstrates the use of `array_count_values` to efficiently determine the frequency of each unique value in an array. It takes an array (either numerically indexed or associative) and returns an associative array where the keys are the unique values from the input array, and the values are their respective counts. This function is incredibly useful for quick statistical analysis, like finding the most common items or occurrences of specific data points.