PHP
Divide an Array into Smaller Chunks or Batches
Learn to split a large PHP array into multiple smaller arrays of a specified size, useful for pagination, batch processing, or UI display using array_chunk.
<?php
$numbers = range(1, 10);
print_r($numbers);
/*
Output:
Array
(
[0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5
[5] => 6 [6] => 7 [7] => 8 [8] => 9 [9] => 10
)
*/
// Split into chunks of 3 elements
$chunks = array_chunk($numbers, 3);
print_r($chunks);
/*
Output:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
[1] => 8
[2] => 9
)
[3] => Array
(
[0] => 10
)
)
*/
// Split into chunks of 4 elements, preserving original keys
$letters = ['a' => 'alpha', 'b' => 'beta', 'c' => 'gamma', 'd' => 'delta', 'e' => 'epsilon'];
$keyedChunks = array_chunk($letters, 2, true);
print_r($keyedChunks);
/*
Output:
Array
(
[0] => Array
(
[a] => alpha
[b] => beta
)
[1] => Array
(
[c] => gamma
[d] => delta
)
[2] => Array
(
[e] => epsilon
)
)
*/
How it works: The `array_chunk()` function allows you to split a single array into multiple smaller arrays (chunks), each containing a specified number of elements. This is incredibly useful for tasks like pagination, processing data in batches, or displaying items in a grid layout. The third optional parameter, `preserve_keys`, determines whether the original keys are maintained in the chunks or if the new chunks are re-indexed numerically.