Roman
Roman

Reputation: 1168

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?

Upvotes: 4

Views: 814

Answers (4)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

You can use call_user_func_array along witharray_reverse and array_chunk to achieve your goal like as

$arr = [11,12,13,14,15,16];
$result = call_user_func_array('array_merge',array_reverse(array_chunk(array_reverse($arr), 2)));
print_r($result);

Fiddle

Upvotes: 1

danbahrami
danbahrami

Reputation: 1012

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;
}

Upvotes: 1

mario
mario

Reputation: 145482

A common trick is utilizing array_merge via call_user_func_array.

$array = call_user_func_array("array_merge", $chunks);

Which will call array_merge with whatever list of $chunks[0], $chunks[1], $chunks[…] as parameters.

You could simplify your arrayReverse function with array_map likewise, btw:

$chunks = array_chunk($array, $size);
$chunks = array_map("array_reverse", $chunks);

Upvotes: 0

viral
viral

Reputation: 3743

Use

$input = call_user_func_array('array_merge', $input);

to flatten the array


But, your code can be simplified as below,

function reverseArray($array, $size)
{
    return call_user_func_array('array_merge', array_map('array_reverse', array_chunk($array, $size)));
}

Upvotes: 0

Related Questions