array_chunk
Splits an array into a list of smaller arrays of a given maximum size.
array_chunk(array $array, int $length, bool $preserve_keys = false): array- Added in PHP 4.2.0
Parameters
| Parameter | Type | Description |
|---|---|---|
$array | array | The array to split. |
$length | int | The maximum number of elements in each chunk. Must be 1 or greater. |
$preserve_keysoptional | bool= false | When true the original keys are kept inside each chunk; when false each chunk is re-indexed from zero. |
Return value
arrayA numerically indexed array of chunks, each containing at most $length elements. The final chunk may be shorter.
Errors
Throws a ValueError if $length is less than 1.
Changelog
- PHP 8.0.0A ValueError is thrown when $length is less than 1. Previously an E_WARNING was raised and the function returned null.
array_chunk() cuts one array into a list of smaller arrays, each holding at most $length elements, in the original order. The last chunk holds whatever is left over, so it is often shorter than the rest. The outer array is always a clean list indexed from zero.
When to reach for it
Reach for it whenever something downstream has a limit. Batching database inserts so a query stays under the placeholder limit, sending 100 IDs at a time to an API that caps request size, writing a CSV in blocks so memory stays flat, or laying out a gallery into rows of three are all one foreach over array_chunk().
What trips people up
By default the keys inside each chunk are thrown away and replaced with 0, 1, 2… That is exactly what you want for a plain list and exactly wrong for an associative array — pass true as the third argument to keep the original keys.
Chunking does not save memory on its own. The function builds the whole nested result in memory before returning it, so for large datasets you still want a generator or a database cursor; use array_chunk() to shape data you already hold.
Example
When to use it
- Batch 10,000 rows into inserts of 500 so a single query does not exceed placeholder limits
- Split a list of user IDs into groups of 100 for an API that caps each request
- Lay a product list out into rows of three for a grid template
Frequently asked questions
How do I keep array keys when using array_chunk?
Pass true as the third argument: array_chunk($array, 2, true). Without it, every chunk is re-indexed from zero and string keys are lost.
What happens if the array does not divide evenly?
The last chunk simply contains the remaining elements and is smaller than the others. array_chunk never pads — use array_pad() on the final chunk if you need a fixed width.
What is the difference between array_chunk and array_slice?
array_chunk splits the whole array into every group of a given size at once, while array_slice extracts one specific range that you choose by offset and length.
More examples
Keeping the original keys
The first result loses every key and shows 0 and 1 inside each chunk. The second keeps 'host'/'port' and 'user'/'ssl', which is the only usable form when the array is associative.
<?php
$settings = ['host' => 'db1', 'port' => 5432, 'user' => 'app', 'ssl' => 'on'];
echo "default:\n";
print_r(array_chunk($settings, 2));
echo "preserved:\n";
print_r(array_chunk($settings, 2, true));Building a grid of rows
Rows of three fall straight out of the chunking. The final chunk only has two items, so array_pad() fills the gap with a placeholder and every printed row stays the same width.
<?php
$products = ['Mouse', 'Keyboard', 'Monitor', 'Cable', 'Dock'];
foreach (array_chunk($products, 3) as $row) {
echo '| ' . implode(' | ', array_pad($row, 3, '—')) . " |\n";
}A chunk size below 1 throws
Since PHP 8.0 a length of 0 or a negative length is a hard ValueError rather than a warning plus null, so a computed batch size must be validated first. An empty input is fine and simply returns an empty array.
<?php
try {
array_chunk([1, 2, 3], 0);
} catch (ValueError $e) {
echo "ValueError: ", $e->getMessage(), "\n";
}
print_r(array_chunk([], 2));
Discussion