How to count values from a PHP array and show value only once in a foreach loop?

In PHP, you can count duplicate values in an array and display each unique value only once using the built-in array_count_values() function. This function returns an associative array where keys are the original values and values are their occurrence counts.

Using array_count_values()

The array_count_values() function automatically counts all occurrences of each value in the array ?

<?php
$listOfNames = array('John','David','Mike','David','Mike','David');
$frequencyOfEachName = array_count_values($listOfNames);
print_r($frequencyOfEachName);
?>
Array ( [John] => 1 [David] => 3 [Mike] => 2 )

Using foreach Loop with Counting Logic

Alternatively, you can manually count values using a foreach loop ?

<?php
$listOfNames = array('John','David','Mike','David','Mike','David');
$countArray = array();

foreach($listOfNames as $name) {
    if(isset($countArray[$name])) {
        $countArray[$name]++;
    } else {
        $countArray[$name] = 1;
    }
}

print_r($countArray);
?>
Array ( [John] => 1 [David] => 3 [Mike] => 2 )

Displaying Results in a Readable Format

You can format the output using a foreach loop to display the counts in a more readable way ?

<?php
$listOfNames = array('John','David','Mike','David','Mike','David');
$frequencyOfEachName = array_count_values($listOfNames);

foreach($frequencyOfEachName as $name => $count) {
    echo $name . " appears " . $count . " time(s)" . "<br>";
}
?>
John appears 1 time(s)
David appears 3 time(s)
Mike appears 2 time(s)

Conclusion

The array_count_values() function is the most efficient way to count duplicate values in PHP arrays. It automatically handles the counting logic and returns a clean associative array with unique values as keys and their counts as values.

Updated on: 2026-03-15T09:37:01+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements