PHP

Count Value Frequencies in a PHP Array

Learn to effortlessly count how many times each unique value appears in a PHP array using the `array_count_values()` function, perfect for statistics and data analysis.

<?php
$data = [
    'apple', 'banana', 'orange', 'apple', 'grape',
    'banana', 'apple', 'kiwi', 'orange', 'mango'
];

// Using array_count_values to count occurrences
$counts = array_count_values($data);
/*
Result:
[
    'apple' => 3,
    'banana' => 2,
    'orange' => 2,
    'grape' => 1,
    'kiwi' => 1,
    'mango' => 1
]
*/

$surveyResults = [1, 5, 2, 1, 3, 5, 1, 4, 2, 5];
$voteCounts = array_count_values($surveyResults);
/*
Result:
[
    1 => 3,
    5 => 3,
    2 => 2,
    3 => 1,
    4 => 1
]
*/

echo "Fruit Counts: " . json_encode($counts) . "
";
echo "Survey Vote Counts: " . json_encode($voteCounts) . "
";

// Example with invalid value type (object) - will throw a warning
// $invalidArray = ['a', new stdClass()];
// $invalidCounts = array_count_values($invalidArray);
?>
How it works: The `array_count_values()` function in PHP counts all the values in an array and returns an associative array where the keys are the original array's unique values, and the values are their respective frequencies. This is highly efficient for determining the distribution or popularity of items within a dataset. Note that array values must be strings or integers for this function to work correctly.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs