How to count the consecutive duplicate values in an array with PHP

1 Answer

0 votes
$arr = array(1,1,1,1,1,3,3,1,1,2,2,2,3,3,3,4,4);
 
$result = array();
$consecutive = array('value' => null, 'total' => null);

foreach ($arr as $val) {
    if ($consecutive['value'] != $val) {
        unset($consecutive);
        $consecutive = array('value' => $val, 'total' => 0);
        $result[] =& $consecutive;
    }

    $consecutive['total']++;
}


print_r($result);

 
 
 
 
/*
run:
 
Array
(
    [0] => Array
        (
            [value] => 1
            [total] => 5
        )

    [1] => Array
        (
            [value] => 3
            [total] => 2
        )

    [2] => Array
        (
            [value] => 1
            [total] => 2
        )

    [3] => Array
        (
            [value] => 2
            [total] => 3
        )

    [4] => Array
        (
            [value] => 3
            [total] => 3
        )

    [5] => Array
        (
            [value] => 4
            [total] => 2
        )
)
 
*/

 



answered Jul 12, 2023 by avibootz
...