Split array into chunks

suggest change

array_chunk() splits an array into chunks

Let’s say we have the following one-dimensional array:

$input_array = array('a', 'b', 'c', 'd', 'e');

Now using array_chunk() on above PHP array,

$output_array = array_chunk($input_array, 2);

The code above makes chunks of 2 elements and creates a multidimensional array, as follows.

Array
(
    [0] => Array
        (
            [0] => a
            [1] => b
        )

    [1] => Array
        (
            [0] => c
            [1] => d
        )

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

)

If the elements are not evenly divided by the chunk size, the last element of the output array contains the remaining elements.


If the size is less than 1, PHP before 8 raised an E_WARNING and returned null. Since PHP 8, array_chunk() throws ValueError.

Parameter Details
$array (array) Input array, the array to work on
$size (int) Size of each chunk (integer value)
$preserve_keys (boolean) (optional) If you want the output array to preserve the keys, set it to TRUE, otherwise FALSE.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents