Split array into chunks of alternating sizes

Issue

I have an array:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
    [8] => 8
    [9] => 9
)

I want to split the array into alternating chunks. (size 2 then 3 then 2 then 3 etc)

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

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

    [2] => Array
        (
            [0] => 5
            [1] => 6
            [2] => 7
        )

    [3] => Array
        (
            [0] => 8
            [1] => 9
        )

)

Solution

That should work:

$a = array(0 => 0,1 => 1,2 => 2,3 => 3,4 => 4, 5 => 5, 6 => 6,7 => 7,8 => 8,9 => 9);
$chunks = array();
$i=1;
while(count($a)){
    $chunks[] = array_splice($a, 0,(2+($i%2)),array());

    $i++;
}

echo "<pre>";
var_dump($chunks);

Answered By – István Őri

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published