How to Use array_chunk in PHP: Syntax and Examples
Use
array_chunk(array $array, int $size, bool $preserve_keys = false) to split an array into smaller arrays each with a maximum of $size elements. It returns a multidimensional array with chunks. Set $preserve_keys to true to keep original keys.Syntax
The array_chunk function splits an array into smaller arrays (chunks) of a specified size.
$array: The input array to split.$size: The maximum number of elements in each chunk.$preserve_keys(optional): Iftrue, original keys are preserved; otherwise, keys are reindexed starting from 0.
php
array_chunk(array $array, int $size, bool $preserve_keys = false): array
Example
This example shows how to split an array of numbers into chunks of 3 elements each. It also demonstrates preserving keys.
php
<?php $input = ["a" => 1, "b" => 2, "c" => 3, "d" => 4, "e" => 5]; // Split into chunks of 3 without preserving keys $chunks = array_chunk($input, 3); print_r($chunks); // Split into chunks of 3 preserving keys $chunks_preserved = array_chunk($input, 3, true); print_r($chunks_preserved); ?>
Output
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
)
)
Array
(
[0] => Array
(
[a] => 1
[b] => 2
[c] => 3
)
[1] => Array
(
[d] => 4
[e] => 5
)
)
Common Pitfalls
Common mistakes when using array_chunk include:
- Forgetting that keys are reindexed by default, which can cause issues if keys matter.
- Setting chunk size to zero or negative, which causes a warning and returns
false. - Expecting the function to modify the original array (it returns a new array instead).
php
<?php // Wrong: chunk size zero causes warning and returns false $result = @array_chunk([1,2,3], 0); var_dump($result); // bool(false) // Right: use positive chunk size $result = array_chunk([1,2,3], 2); print_r($result); ?>
Output
Warning: array_chunk(): Size parameter expected to be greater than 0 in ...
bool(false)
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 3
)
)
Quick Reference
| Parameter | Description | Default |
|---|---|---|
| $array | Input array to split | Required |
| $size | Maximum elements per chunk | Required |
| $preserve_keys | Keep original keys if true | false |
Key Takeaways
Use array_chunk to split arrays into smaller arrays of a fixed size.
By default, keys are reindexed; set preserve_keys to true to keep original keys.
Chunk size must be a positive integer to avoid warnings.
array_chunk returns a new array and does not modify the original.
Useful for processing large arrays in smaller parts.