PHP

Split an Array into Chunks of a Specific Size

Learn how to divide a large PHP array into smaller, more manageable sub-arrays (chunks) of a specified size using `array_chunk`, ideal for pagination or batch processing.

<?php
function splitArrayIntoChunks(array $array, int $chunkSize, bool $preserveKeys = false): array
{
    // array_chunk splits an array into new arrays.
    // The first parameter is the input array.
    // The second parameter is the size of each chunk.
    // The third (optional) parameter, if set to true, will preserve the original keys.
    // If false (default), each chunk will be re-indexed numerically from zero.
    return array_chunk($array, $chunkSize, $preserveKeys);
}

$numbers = range(1, 10); // [1, 2, ..., 10]
$chunkedNumbers = splitArrayIntoChunks($numbers, 3);
// var_dump($chunkedNumbers);
// Expected:
// array(4) {
//   [0]=> array(3) { [0]=> int(1), [1]=> int(2), [2]=> int(3) }
//   [1]=> array(3) { [0]=> int(4), [1]=> int(5), [2]=> int(6) }
//   [2]=> array(3) { [0]=> int(7), [1]=> int(8), [2]=> int(9) }
//   [3]=> array(1) { [0]=> int(10) }
// }

$associativeData = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];
$chunkedAssociativePreservingKeys = splitArrayIntoChunks($associativeData, 2, true);
// var_dump($chunkedAssociativePreservingKeys);
// Expected:
// array(3) {
//   [0]=> array(2) { ["a"]=> int(1), ["b"]=> int(2) }
//   [1]=> array(2) { ["c"]=> int(3), ["d"]=> int(4) }
//   [2]=> array(1) { ["e"]=> int(5) }
// }
?>
How it works: This `splitArrayIntoChunks` function utilizes PHP's built-in `array_chunk` function to divide an input array into smaller arrays (chunks) of a specified size. It's particularly useful for tasks like pagination, processing data in batches, or displaying elements in a grid layout. The optional `$preserveKeys` parameter allows maintaining the original array keys within each chunk.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs