phparraysgroupingcounting

Group and count streaks of repeated values in a flat array


I need to count the "streaks" of repeated values in a flat array.

Sample input array:

['A', 'A', 'B', 'B', 'C', 'A', 'A']

I need an array like:

array(
    'A' => (count1 => 2, count2 => 2),
    'B' => (count1 => 2),
    'C' => (count1 => 1)
)

Solution

  • $data = array(0=>A,1=>A,2=>B,3=>B,4=>C,5=>A,6=>A);
    
    $counters = array();
    $prev = NULL;
    array_walk(
        $data,
        function ($entry) use (&$prev, &$counters) {
            if ($entry !== $prev) {
                $prev = $entry;
                $counters[] = 1;
            } else {
                $counters[count($counters)-1]++;
            }
        }
    );
    var_dump($counters);