Search code examples
phparrayskeygrouping

Split flat array into grouped subarrays containing values from consecutive key in the input array


I have an array from array_diff function and it looks like below:

Array
(
    [0] => world
    [1] => is
    [2] => a
    [3] => wonderfull
    [5] => in
    [6] => our
)

As you can see, we have a gap between the keys #3 and #5 (i.e. there is no key #4). How can I split that array into 2 parts, or maybe more if there are more gaps? The expected output would be:

Array
    (
        [0] => Array
        (
           [0] => world
           [1] => is
           [2] => a
           [3] => wonderfull
        )
        [1] => Array 
        (
           [0] => in
           [1] => our
        ) 
    )

Solution

  • You can use old_key,new_key concept to check that there difference is 1 or not? if not then create new index inside you result array otherwise add the values on same index:-

    <?php
    
    $arr = Array(0 => 'world',1 => 'is',2 => 'a',3 => 'wonderfull',5 => 'in',6 => 'our');
    
    $new_array = [];
    $old_key = -1;
    $i = 0;
    foreach($arr as $key=>$val){
        if(($key-$old_key) ==1){
            $new_array[$i][] = $val;
            $old_key = $key;
        }
        if(($key-$old_key) >1){
             $i++;
             $new_array[$i][] = $val;
             $old_key = $key;
        }
    }
    print_r($new_array);
    

    https://3v4l.org/Yl9rp