Split an array into chunks of a specified size.
The array_chunk() function splits an array into arrays of the given size. The last chunk may contain fewer elements if the array cannot be divided evenly.
When preserve_keys is set to true, the original keys are preserved in each chunk. By default, keys are re-indexed numerically starting from zero in each chunk.
This function is useful for paginating data, processing items in batches, or splitting data into groups for display purposes.
| Name | Description | Optional |
|---|---|---|
array |
The array to split. | No |
length |
The size of each chunk. | No |
preserve_keys |
Whether to preserve original keys. | Yes |
$data = [1, 2, 3, 4, 5];
$chunks = array_chunk($data, 2);
// [[1, 2], [3, 4], [5]]