I'm nidhin I'm nidhin - 6 months ago 28
PHP Question

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

Answer

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'));
Comments