Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count of duplicate elements in an array in php

Hi, How can we find the count of duplicate elements in a multidimensional array ?

I have an array like this

Array
(
    [0] => Array
        (
            [lid] => 192
            [lname] => sdsss
        )

    [1] => Array
        (
            [lid] => 202
            [lname] =>  testing
        )

    [2] => Array
        (
            [lid] => 192
            [lname] => sdsss
        )

    [3] => Array
        (
            [lid] => 202
            [lname] =>  testing
        )

)

How to find the count of each elements ?

i.e, count of entries with id 192,202 etc

like image 887
I'm nidhin Avatar asked Nov 16 '12 09:11

I'm nidhin


People also ask

How do you count the number of repeated elements in an array in PHP?

The array_count_values() function returns an array with the number of occurrences for each value. It returns an associative array. The returned array has keys as the array's values, whereas values as the count of the passed values.

How do I count items in an array PHP?

You can simply use the PHP count() or sizeof() function to get the number of elements or values in an array. The count() and sizeof() function returns 0 for a variable that has been initialized with an empty array, but it may also return 0 for a variable that isn't set.

What is the use of Array_count_values () in PHP explain with example?

The array_count_values() function is used to count all the values inside an array. In other words, we can say that array_count_values() function is used to calculate the frequency of all of the elements of an array.


2 Answers

You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid'] member and then use array_count_value() to do the counting for you.

array_count_values(array_map(function($item) {
    return $item['lid'];
}, $arr);

Plus, it's a one-liner, thus adding to elite hacker status.

Update

Since 5.5 you can shorten it to:

array_count_values(array_column($arr, 'lid'));
like image 184
Ja͢ck Avatar answered Oct 11 '22 16:10

Ja͢ck


foreach ($array as $value) 
{
    $numbers[$value[lid]]++;
}
foreach ($numbers as $key => $value) 
{
    echo 'numbers of '.$key.' equal '.$value.'<br/>';
}
like image 2
Cedrun Avatar answered Oct 11 '22 16:10

Cedrun