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
Syntax
array_chunk(array $array, int $length, bool $preserve_keys = false): array
Parameters
| Parameter | Description |
|---|---|
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
<?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
)
)<?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
| Version | Change |
|---|---|
| PHP 4.2 | Added |
Related
array_slice()· Return a portion of an array without changing the original, given an offset and an optional length.str_split()· Split a string into an array of chunks of a given length, one byte each by default. Use mb_str_split() for UTF-8.- PHP Arrays · tutorial
- PHP Array Functions · tutorial