How to Split an Array in PHP Using array_chunk
In PHP, managing large datasets often requires breaking them down
into smaller, more manageable pieces for processing, pagination, or
grid-based layouts. This article provides a quick and clear guide on how
to use the built-in array_chunk() function to split a
single array into multiple smaller arrays of a specified size, complete
with practical code examples.
Understanding the array_chunk() Syntax
The array_chunk() function takes an input array and
splits it into numerical chunks based on a defined size.
Here is the basic syntax of the function:
array_chunk(array $array, int $length, bool $preserve_keys = false): array$array: The input array you want to split.$length: An integer defining the maximum size of each chunk. The last chunk may contain fewer elements if the total array size is not perfectly divisible by the length.$preserve_keys: An optional boolean parameter. When set tofalse(default), the new chunks are reindexed numerically starting from 0. When set totrue, the original keys from the input array are preserved.
Basic Example: Splitting an Array
In this example, we split an array of five elements into chunks of two. Because the total number of elements is not divisible by two, the final chunk will contain the remaining single element.
<?php
$input_array = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
// Split the array into chunks of 2
$chunks = array_chunk($input_array, 2);
print_r($chunks);
?>Output:
Array
(
[0] => Array
(
[0] => apple
[1] => banana
)
[1] => Array
(
[0] => cherry
[1] => date
)
[2] => Array
(
[0] => elderberry
)
)
Example: Preserving Original Keys
By default, array_chunk() resets the keys of the
elements within each chunk. If you are working with an associative array
or need to maintain the original numerical indexes, set the third
parameter to true.
<?php
$user_scores = [
'Alice' => 95,
'Bob' => 88,
'Charlie' => 91,
'David' => 79
];
// Split the associative array into chunks of 2, preserving keys
$chunks = array_chunk($user_scores, 2, true);
print_r($chunks);
?>Output:
Array
(
[0] => Array
(
[Alice] => 95
[Bob] => 88
)
[1] => Array
(
[Charlie] => 91
[David] => 79
)
)