PHP
Splitting an Array into Fixed-Size Chunks for Processing or Display
Efficiently divide a large PHP array into smaller, manageable chunks using `array_chunk()`, perfect for pagination, batch processing, or displaying data in a grid layout.
<?php
$numbers = range(1, 20);
// Split the array into chunks of 5 elements
$chunks = array_chunk($numbers, 5);
echo "Array split into chunks of 5:
";
print_r($chunks);
/*
Output:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
[1] => Array
(
[0] => 6
[1] => 7
[2] => 8
[3] => 9
[4] => 10
)
[2] => Array
(
[0] => 11
[1] => 12
[3] => 13
[4] => 14
[5] => 15
)
[3] => Array
(
[0] => 16
[1] => 17
[2] => 18
[3] => 19
[4] => 20
)
)
*/
echo "
";
// Preserve keys when chunking (useful for associative arrays)
$associativeArray = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6];
$chunksWithKeys = array_chunk($associativeArray, 2, true);
echo "Associative array split into chunks of 2, preserving keys:
";
print_r($chunksWithKeys);
/*
Output:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
)
[1] => Array
(
[c] => 3
[d] => 4
)
[2] => Array
(
[e] => 5
[f] => 6
)
)
*/
How it works: The `array_chunk()` function is highly useful for breaking down a large array into smaller, more manageable sub-arrays. It takes the original array, the desired chunk size, and an optional boolean to preserve keys. This is invaluable for implementing pagination, processing data in batches (e.g., sending emails to groups of users), or displaying items in a multi-column layout on a webpage.