PHP

Split a PHP Array into Smaller Chunks

Learn to divide a large PHP array into smaller, manageable chunks using `array_chunk()`. Perfect for pagination, batch processing, or displaying data in rows.

<?php

$items = ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape', 'honeydew'];
$chunkSize = 3;

$chunks = array_chunk($items, $chunkSize);

print_r($chunks);
/* Expected Output:
Array
(
    [0] => Array
        (
            [0] => apple
            [1] => banana
            [2] => cherry
        )

    [1] => Array
        (
            [0] => date
            [1] => elderberry
            [2] => fig
        )

    [2] => Array
        (
            [0] => grape
            [1] => honeydew
        )

)
*/

$preserveKeysChunks = array_chunk($items, $chunkSize, true); // Preserve keys
print_r($preserveKeysChunks);
/* Expected Output (with preserved keys):
Array
(
    [0] => Array
        (
            [0] => apple
            [1] => banana
            [2] => cherry
        )

    [1] => Array
        (
            [3] => date
            [4] => elderberry
            [5] => fig
        )

    [2] => Array
        (
            [6] => grape
            [7] => honeydew
        )

)
*/

?>
How it works: The `array_chunk()` function is used to split an array into several smaller arrays (chunks). It takes the original array and a desired `chunk_size` as arguments. Optionally, a third boolean argument can be passed to preserve the original array's keys within the chunks. This is particularly useful for tasks like pagination, processing data in batches (e.g., sending emails to groups of users), or structuring data for display in multi-column layouts where you need to group items.

Need help integrating this into your project?

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

Hire DigitalCodeLabs