Home » PHP

Find occurrences of each element in an array using array_count_values() in PHP



PHP array_count_values() function with Example: Here, we will learn how to find occurrences of each element in PHP?
Submitted by IncludeHelp, on January 09, 2018

Given an array, we have to find occurrences of each element in PHP.

PHP - array_count_values() function

Function will count the occurrences of each individual element and returns an array with elements (key-value) and its occurrences.

Syntax:

array_count_values($arr)

Here, $arr is an array.

Example:

    Input: array(10,20,30,30,20,10,50);
    Output:
    Array
    (
        [10] => 2
        [20] => 2
        [30] => 2
        [50] => 1
    )


    Input: array("New Delhi", "New Delhi", "Mumbai");
    Output:
    Array
    (
        [New Delhi] => 2
        [Mumbai] => 1
    )

PHP code

<?php
    //array 1 with integer elements 
    $arr1 = array(10,20,30,30,20,10,50);
    print_r(array_count_values($arr1));
    
    //array 2 with string values
    $arr2 = array("New Delhi", "New Delhi", "Mumbai");
    print_r(array_count_values($arr2));    
?>

Output

Array
(
    [10] => 2
    [20] => 2
    [30] => 2
    [50] => 1
)
Array
(
    [New Delhi] => 2
    [Mumbai] => 1
)





Quick links:
C FAQ(s) C Advance programs C/C++ Tips & Tricks Puzzles JavaScript CSS Python Linux Commands PHP Android Articles More...

Was this page helpful? Please share with your friends...

Are you a blogger? Join our Blogging forum.




Comments and Discussions





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com (2015-2018), Some rights reserved.