← Back to all snippets
PHP

Counting Value Occurrences in an Array

Discover how to efficiently count the frequency of all unique values within a single-dimensional PHP array using the built-in array_count_values() function for quick statistics.

<?php
$fruits = ['apple', 'banana', 'orange', 'apple', 'grape', 'banana', 'apple'];
$colors = ['red', 'blue', 'green', 'red', 'yellow', 'blue'];

$fruitCounts = array_count_values($fruits);
$colorCounts = array_count_values($colors);

echo "Fruit Counts:
";
print_r($fruitCounts);

echo "
Color Counts:
";
print_r($colorCounts);
?>
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 original array's values and the values are their respective counts. This function is very handy for generating frequency distributions, statistics, or summaries from a list of items, such as determining the most common fruit or color in a dataset.

Need help integrating this into your project?

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

Hire DigitalCodeLabs