PHP

Split Large Array into Smaller Chunks

Efficiently divide a large PHP array into smaller, manageable arrays of a specified size using `array_chunk`, ideal for pagination or batch processing.

<?php
$numbers = range(1, 15); // Create an array from 1 to 15

// Chunk the array into pieces of 4 elements
$chunks = array_chunk($numbers, 4);

echo "Array chunks (size 4):
";
print_r($chunks);
/* Expected 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
        )

)
*/

// Chunk the array into pieces of 3 elements, preserving keys
$associativeData = [
    'a' => 'Apple', 'b' => 'Banana', 'c' => 'Cherry',
    'd' => 'Date', 'e' => 'Elderberry', 'f' => 'Fig',
    'g' => 'Grape', 'h' => 'Honeydew'
];

$chunksPreservingKeys = array_chunk($associativeData, 3, true); // true for preserve_keys
echo "
Array chunks (size 3, preserving keys):
";
print_r($chunksPreservingKeys);
/* Expected output:
Array
(
    [0] => Array
        (
            [a] => Apple
            [b] => Banana
            [c] => Cherry
        )

    [1] => Array
        (
            [d] => Date
            [e] => Elderberry
            [f] => Fig
        )

    [2] => Array
        (
            [g] => Grape
            [h] => Honeydew
        )

)
*/
?>
How it works: The `array_chunk` function efficiently divides an array into new arrays (chunks) of a specified size. It's particularly useful for tasks like pagination, processing data in batches, or displaying elements in a grid. The first argument is the input array, and the second is the desired `size` of each chunk. An optional third boolean argument, `preserve_keys`, determines whether the original array keys are maintained (true) or reset to numeric indices (false, default) in the new chunks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs