Search code examples
phparrayschunksarray-reverse

Split flat array into chunks of n elements, then reverse the order within each chunk


I want to reverse an array by two elements in each step. If I have an array [11,12,13,14,15,16], I want to reverse first two elements [11,12] and then another two elements [13,14] etc. The final array should be [12,11,14,13,16,15]; My code is below:

function reverseArray($array, $size){
    $reversed_array = array();

    $chunk = array_chunk($array, $size);
    $chunk_length = count($chunk);  
    for($i = 0; $i < $chunk_length; $i++){
        $reversed_array[$i] = array_reverse( ($chunk[$i]) );            
    }

    return $reversed_array;
}

$array = array(12,13,14,15);
$size = 2;
print_r(reverseArray($array,$size));


Array
(
    [0] => Array
        (
            [0] => 13
            [1] => 12
        )

    [1] => Array
        (
            [0] => 15
            [1] => 14
        )

)

How can I merge those two arrays into one? I tried to use array_merge but don't know how to use it in my function. Any idea?


Solution

  • function reverseArray($array, $size){
        $reversed_array = array();
    
        $chunk = array_chunk($array, $size);
        $chunk_length = count($chunk);  
        for($i = 0; $i < $chunk_length; $i++){
            $reversed_array = array_merge($reversed_array,array_reverse( ($chunk[$i]) ));            
        }
    
        return $reversed_array;
    }