C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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
)


Advertisements




Liked this article? Do share with your friends :)


COMMENTS