virepo virepo - 2 months ago 13
PHP Question

How to reverse every 4 items of an array in PHP?

I have a simple array that looks like this:

Array (
[0] => Array (
[id] => 8692
[name] => d
)
[1] => Array (
[id] => 8691
[name] => c
)
[2] => Array (
[id] => 8690
[name] => b
)
[3] => Array (
[id] => 8689
[name] => a
)
[4] => Array (
[id] => 8500
[name] => d
)
[5] => Array (
[id] => 8499
[name] => c
)
[6] => Array (
[id] => 8498
[name] => b
)
[7] => Array (
[id] => 8497
[name] => a
)
)


This array is quite long so I only included the first 4 items to give you an idea.

My problem is that I need the array to be in a format of

a,b,c,d,a,b,c,d


At the moment the format is like:

d,c,b,a,d,c,b,a


By this I mean the ['name'] value which is either a,b,c or d.

So I every 4 items in the array need to be reversed.

I have tried to achieve this but fail every time ending up with lots of for & while loops.

Answer

You can do it using array_chunk, array_merge and array_reverse:

$finalArray = array();

$arrays = array_chunk($myArray, 4);

foreach ($arrays as $array) {
    $finalArray = array_merge($finalArray, array_reverse($array));
}