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

PHP array_count_values() work with Example: Here, we will figure out how to discover events of every component in PHP?

Given a cluster, we need to discover events of every component in PHP.

PHP – array_count_values() work

Capacity will check the events of every individual component and returns a cluster with components (key-value) and its events.

Syntax:

array_count_values($arr)

Here, $arr is a cluster.

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("Bilaspur", "Raipur", "Bahatrai");
    print_r(array_count_values($arr2));    
?>

Output:

Array
(
    [10] => 2
    [20] => 2
    [30] => 2
    [50] => 1
)
Array
(
    [Raipur] => 2
    [Bahatrai] => 1
)

Leave a Comment

error: Alert: Content is protected!!