PHP Function Reference

PHP array_chunk() Function



The PHP array_chunk() function chunks an array into arrays with specified length elements. The last chunk may contain less than length elements.

Syntax

array_chunk(array, length, preserve_keys)

Parameters

array Required. Specify the array to work on.
length Required. Specify the size of each chunk.
preserve_keys Optional. Specify true to preserve the keys. Default is false which reindexes the chunk numerically.

Return Value

Returns a multi-dimensional numerically indexed array, starting with zero, with each dimension containing length elements.

Exceptions

Throws E_WARNING if the length is less than 1 and returns null.

Example:

The example below shows the usage of array_chunk() function.

<?php
$Arr = array("A", "B", "C", "D", "E");

//using array_chunk function
print_r(array_chunk($Arr, 2));
echo "\n";
print_r(array_chunk($Arr, 2, true));
?>

The output of the above code will be:

Array
(
    [0] => Array
        (
            [0] => A
            [1] => B
        )

    [1] => Array
        (
            [0] => C
            [1] => D
        )

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

Array
(
    [0] => Array
        (
            [0] => A
            [1] => B
        )

    [1] => Array
        (
            [2] => C
            [3] => D
        )

    [2] => Array
        (
            [4] => E
        )
)

❮ PHP Array Reference