PHP

Count Occurrences of Each Value in an Array

Use `array_count_values()` to quickly count how many times each unique value appears in an array, returning an associative array of counts for analysis.

<?php
$fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
$counts = array_count_values($fruits);
print_r($counts);

$numbers = [1, 5, 2, 5, 1, 3, 1];
$numberCounts = array_count_values($numbers);
print_r($numberCounts);
?>
How it works: The `array_count_values()` function is a simple yet powerful way to tally the frequency of each unique value within an array. It returns an associative array where the keys are the unique values from the original array and the corresponding values are their respective counts. This is invaluable for statistics, data analysis, or determining popular items from a list in web applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs