Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to count values from a PHP array and show value only once in a foreach loop?
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
<!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 )
Advertisements
