PHP
Split an Array into Chunks (Pagination/Batching)
Discover how to divide a large PHP array into smaller, manageable chunks, ideal for pagination, batch processing, or displaying data.
<?php
$numbers = range(1, 15); // Creates an array from 1 to 15
echo "<h3>Original Array:</h3><pre>";
print_r($numbers);
echo "</pre>";
// Split into chunks of 4 elements
$chunks = array_chunk($numbers, 4);
echo "<h3>Chunks of 4:</h3><pre>";
print_r($chunks);
echo "</pre>";
/*
Output:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
[1] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)
[2] => Array
(
[0] => 9
[1] => 10
[2] => 11
[3] => 12
)
[3] => Array
(
[0] => 13
[1] => 14
[2] => 15
)
)
*/
// Split into chunks of 3, preserving keys
$data = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7];
$chunksPreservingKeys = array_chunk($data, 3, true);
echo "<h3>Chunks of 3 (preserving keys):</h3><pre>";
print_r($chunksPreservingKeys);
echo "</pre>";
/*
Output:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
[c] => 3
)
[1] => Array
(
[d] => 4
[e] => 5
[f] => 6
)
[2] => Array
(
[g] => 7
)
)
*/
How it works: The `array_chunk()` function splits an array into smaller chunks (new arrays). It takes the input array, the `size` of each chunk, and an optional boolean parameter `preserve_keys`. If `preserve_keys` is set to `true`, the original keys will be maintained in the new chunks; otherwise, each chunk will be re-indexed numerically from zero. This is incredibly useful for pagination, processing data in batches, or displaying grid layouts.