Search code examples
phparraysslicechunks

Split a flat array into arrays of n elements


There is an array containing K elements. What's the best way to get chunks of N < K items from this array?

Example input:

$x = [1,2,3,4,5,6,7,8,9,10]; // K = 10

Desired result, when N = 3;

$x1 = [1,2,3];
$x2 = [4,5,6];
$x3 = [7,8,9];
$x4 = [10];

Obviously, there is no need to store the result in variables. As long as it's possible to process it by foreach (or any other iteration logic), it should be fine.

The problem with array_slice is that it does not remove the N-slice from the beginning of the array. The problem with array_shift is that it does not support shifting more than 1 item at once. Is there anything more elegant than iterating over array_shift?


Solution

  • array_chunk is what you need.

    <?php
    $x = [1,2,3,4,5,6,7,8,9,10];
    print_r(array_chunk($x,3));
    

    OUTPUT :

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