PHP array_chunk Function: Splitting an Array into Chunks
This article explains PHP’s array_chunk function, describing its parameters, return value, and optional key preservation, and provides clear example code that demonstrates how an input array can be divided into equally sized sub‑arrays.
The array_chunk function splits a given array into multiple sub‑arrays, each containing a number of elements defined by the $size argument; the final chunk may contain fewer elements.
Parameters
$input – the array to be processed.
$size – the number of elements each chunk should contain.
$preserve_keys – optional boolean (default false ). When set to true , the original keys are retained; otherwise, each chunk receives new numeric indexes starting from zero.
Return value
A multidimensional array where each element is a chunk of the original array, indexed from zero.
Example
Output
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
Array
(
[0] => Array
(
[a] => a
[b] => b
)
[1] => Array
(
[c] => c
[d] => d
)
[2] => Array
(
[e] => e
)
)Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.