PHP
Split an Array into Smaller Chunks or Pages
Learn how to easily divide a large PHP array into smaller, more manageable arrays of a specified size, perfect for pagination or batch processing.
<?php
$data = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew'];
$chunkSize = 3;
$chunks = array_chunk($data, $chunkSize);
/*
Output:
Array
(
[0] => Array
(
[0] => apple
[1] => banana
[2] => cherry
)
[1] => Array
(
[0] => date
[1] => elderberry
[2] => fig
)
[2] => Array
(
[0] => grape
[1] => honeydew
)
)
*/
print_r($chunks);
// Example with preserving keys
$associativeData = [
'a' => 'Alice', 'b' => 'Bob', 'c' => 'Charlie',
'd' => 'David', 'e' => 'Eve', 'f' => 'Frank'
];
$chunksPreserveKeys = array_chunk($associativeData, 2, true);
/*
Output:
Array
(
[0] => Array
(
[a] => Alice
[b] => Bob
)
[1] => Array
(
[c] => Charlie
[d] => David
)
[2] => Array
(
[e] => Eve
[f] => Frank
)
)
*/
print_r($chunksPreserveKeys);
?>
How it works: The `array_chunk()` function is a straightforward way to break an array into smaller segments. It takes the input array and a desired `chunkSize`. An optional third boolean parameter, `preserve_keys`, determines whether the original array keys are maintained in the chunks (true) or reset to numeric indices (false, default). This is extremely useful for pagination, processing data in batches, or structuring output in a grid layout.