PHP 8 reference · Array Functions

PHP array_chunk() Function

Split an array into smaller arrays of a given size. The last chunk may be smaller.

PHP 8 Since 4.2

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_chunk(array $array, int $length, bool $preserve_keys = false): array

Parameters

ParameterDescription
array The input array.
length Elements per chunk; must be at least 1.
preserve_keys optional true keeps the original keys. Default: false

Return value

An array of chunks.

Examples

PairsTry it yourself
<?php
print_r(array_chunk([1, 2, 3, 4, 5], 2));

Output

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

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

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

)
Process in batchesTry it yourself
<?php
$ids = range(1, 7);
foreach (array_chunk($ids, 3) as $batch) {
    echo "INSERT batch: ", implode(",", $batch), "\n";
}

Output

INSERT batch: 1,2,3
INSERT batch: 4,5,6
INSERT batch: 7

Version history

VersionChange
PHP 4.2Added

Was this page helpful?