
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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 )
- Related Articles
- Stripping last comma from a foreach loop in PHP?
- PHP foreach Loop.
- How to show a foreach loop using a flow chart in JavaScript?’
- Select a value from MySQL database only if it exists only once from a column with duplicate and non-duplicate values
- Get count of values that only appear once in a MySQL column?
- Find and display duplicate values only once from a column in MySQL
- Foreach loop with two arrays and if-condition evaluation to find matching values PHP?
- How to access and return specific value of a foreach in PHP?
- Multiple index variables in PHP foreach loop
- How to SELECT all values from a table only once if they're duplicated?
- PHP Casting Variable as Object type in foreach Loop
- The internal working of the ‘foreach’ loop in PHP
- Iterating C# StringBuilder in a foreach loop
- How can I count true and false values in my PHP array?
- How to order return duplicate column values only once in MySQL?

Advertisements