PHP
Split a PHP Array into Chunks
Discover how to divide a large PHP array into smaller, more manageable chunks using array_chunk(), useful for pagination or displaying data in columns.
<?php
$items = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew'];
$chunkSize = 3;
$chunks = array_chunk($items, $chunkSize);
print_r($chunks);
/* Output:
Array
(
[0] => Array
(
[0] => apple
[1] => banana
[2] => cherry
)
[1] => Array
(
[0] => date
[1] => elderberry
[2] => fig
)
[2] => Array
(
[0] => grape
[1] => honeydew
)
)
*/
// With preserve_keys set to true
$associativeItems = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry', 'd' => 'date'];
$chunksWithKeys = array_chunk($associativeItems, 2, true);
print_r($chunksWithKeys);
/* Output:
Array
(
[0] => Array
(
[a] => apple
[b] => banana
)
[1] => Array
(
[c] => cherry
[d] => date
)
)
*/
How it works: The `array_chunk()` function splits an array into new arrays, each containing `size` elements. It's particularly useful for paginating results or displaying data in columns. The optional third parameter, `preserve_keys`, determines whether the original keys are preserved (true) or re-indexed numerically (false, default) within each new chunk.