PHP
Count Value Occurrences in a PHP Array
Efficiently count how many times each unique value appears in a PHP array using `array_count_values()`, an indispensable tool for statistics, frequency analysis, and data summarization.
<?php
$fruits = ["apple", "banana", "apple", "orange", "banana", "apple", "kiwi"];
// Count the occurrences of each unique value
$counts = array_count_values($fruits);
print_r($counts);
/*
Output:
Array
(
[apple] => 3
[banana] => 2
[orange] => 1
[kiwi] => 1
)
*/
// Example with mixed types (integer 1 and string '1' are treated distinctly)
$mixedData = [1, "hello", 2, "world", 1, "hello", "1", 3];
$mixedCounts = array_count_values($mixedData);
print_r($mixedCounts);
/*
Output:
Array
(
[1] => 2 // Integer 1
[hello] => 2
[2] => 1
[world] => 1
[1] => 1 // String '1'
[3] => 1
)
Note: PHP may display string '1' as integer key 1 if not explicitly handled for strictness.
For practical purposes, ensure consistent data types if precise counting is needed.
*/
?>
How it works: `array_count_values()` takes an array as input 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 each appeared). This function is extremely useful for generating quick summaries or statistics from lists of data.