phparraysloops

Chunk a flat array into 4 rows with 3 elements each


Just trying to find out if there is a more efficient way of chunking an array; I have an array that could be rather large, and I need to chunk it into multidimensional arrays of 3, but only have 4.

This is what I have so far, and it works; but the question is to see if there is a better/faster alternative.

$rows = array_chunk($array, 3);

$top = array();
for ($i = 0; $i < 3; $i++) {
    $top[] = $rows[$i];
}

Notes

The $rows array looks something like this:

array(
    [0] => name,
    [1] => name,
    [2] => name,
    .....etc
)

And I'd just like to chunk it to look like this:

array(
    [0] => array(
        [0] => name,
        [1] => name,
        [2] => name,
    ),
    [1] => array(
        [0] => name,
        [1] => name,
        [2] => name,
    ),
    [2] => array(
        [0] => name,
        [1] => name,
        [2] => name,
    ),
    [3] => array(
        [0] => name,
        [1] => name,
        [2] => name,
    )
)

And for those who don't bother reading, I do already have something that works (as stated above), I'm just trying to optimize it as it's quite possibly the ugliest way to do it.


Solution

  • //make sure to copy the sliced values into a different array
    $slice = array_slice($array,0,12);
    $rows = array_chunk($slice,3);