Search code examples
phparrayscountflatten

Count total occurrences of each comma-separated value in an array of arrays


I want to extract count of each comma separated word from following array. Tried multiple functions (recursive/non-recursive) but nothing seems to work.

I would like array_count_values() to give the combined count of all keys as 3, but it gives just 1 for each.

Actual Array

Array
(
   [0] => Bangalore, Chennai, Delhi, Gurgaon, Hyderabad, Kolkata, Mumbai / Navi Mumbai, Noida, Guntur
   [1] => Bangalore, Chennai, Delhi, Gurgaon, Hyderabad, Kolkata, Mumbai / Navi Mumbai, Noida, Guntur
   [2] => Bangalore, Chennai, Delhi, Gurgaon, Hyderabad, Kolkata, Mumbai / Navi Mumbai, Noida, Guntur
)

This Link seems to quite close & giving following output

Array
(
   [Bangalore] => 1
   [Chennai] => 1
   [Delhi] => 1
   [Gurgaon] => 1
   [Hyderabad] => 1
   [Kolkata] => 1
   [Mumbai / Navi Mumbai] => 1
   [Noida] => 1
   [Guntur] => 1
)

Required Output

Array
(
   [Bangalore] => 3
   [Chennai] => 3
   [Delhi] => 3
   [Gurgaon] => 3
   [Hyderabad] => 3
   [Kolkata] => 3
   [Mumbai / Navi Mumbai] => 3
   [Noida] => 3
   [Guntur] => 3
)

I know I m very close to required output but not able to fix it.


Solution

  • Couldn't resist coming up with a one-liner ;-)

    $input = array(
        'foo, bar, baz',
        'foo, bar',
        'foo',
    );
    
    $output = array_count_values(call_user_func_array('array_merge', array_map(function($v) { return explode(', ', $v); }, $input)));
    

    Which produces:

    Array
    (
        [foo] => 3
        [bar] => 2
        [baz] => 1
    )