phparraysconcatenationgroupingrepeat

Group consecutively repeated values of a flat array and concatenate the values within each group


How can the array be separated into groups of identical elements (concatenated chars). For example, I have this array:

Array(
    [0] => 1
    [1] => 1
    [2] => 1
    [3] => 2
    [4] => 2
    [5] => 1
)

and want to group all identical numbers in only one element, bringing the together with concatenation to get something like this:

Array(
    [0] => 111
    [1] => 22
    [2] => 1
)

Solution

  • To group all identical elements by concatenating them together (will not work for concatenating just the neighboring identical elements)

    $arr = array (1,1,1,2,2,1);
    $sum = array_count_values($arr);
    array_walk($sum, function(&$count, $value) { 
      $count = str_repeat($value, $count); 
    });
    print_r($sum);
    

    Output

    Array ( [1] => 1111 [2] => 22 )

    Or for concatenating just the neighboring identical elements

    $prev=null; 
    $key=0; 
    foreach ( $arr as $value ) { 
      if ($prev == $value){ 
        $res[$key] .= $value;
      } else { 
        $key++; 
        $res[$key] = $value; 
        $prev=$value; 
      } 
    }
    print_r($res);
    

    Output

    Array ( [1] => 111 [2] => 22 [3] => 1 )