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

PHPServer Side ProgrammingProgramming

Let’s say the following is our PHP array 

$listOfNames = array('John','David','Mike','David','Mike','David');

We want the output to display the count of values in the above array like this −

Array ( [John] => 1 [David] => 3 [Mike] => 2 )

To get the count, use inbuilt function array_count_values().

Example

The PHP code is as follows

 Live Demo

<!DOCTYPE html>
<html>
<body>
<?php
$listOfNames = array('John','David','Mike','David','Mike','David');
$frequencyOfEachName = array_count_values($listOfNames);
print_r( $frequencyOfEachName);
?>
</body>
</html>

Output

This will produce the following output

Array ( [John] => 1 [David] => 3 [Mike] => 2 )
raja
Published on 13-Oct-2020 08:42:36
Advertisements