PHP

Chunk a PHP Array into Smaller Sub-Arrays

Learn to split a large PHP array into smaller, manageable sub-arrays of a specified size using `array_chunk`, perfect for pagination or processing data in batches.

<?php

$items = range(1, 15); // Creates an array from 1 to 15
$chunk_size = 4;

// Basic chunking
$chunks = array_chunk($items, $chunk_size);
echo "Basic chunking (size {$chunk_size}):
";
print_r($chunks);
/* 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
        )

)
*/

$named_items = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5];

// Chunking with preserve_keys = true
$chunks_preserved = array_chunk($named_items, 2, true);
echo "
Chunking with preserved keys (size 2):
";
print_r($chunks_preserved);
/* Output:
Array
(
    [0] => Array
        (
            [a] => 1
            [b] => 2
        )

    [1] => Array
        (
            [c] => 3
            [d] => 4
        )

    [2] => Array
        (
            [e] => 5
        )

)
*/
How it works: The `array_chunk` function is highly useful for dividing a single array into multiple smaller arrays (chunks). This is particularly valuable for scenarios like pagination, where you display a fixed number of items per page, or for processing large datasets in smaller, more manageable batches. The second parameter specifies the desired size of each chunk. The optional third parameter, `preserve_keys` (defaulting to `false`), determines whether the original keys are maintained in the new sub-arrays or if new numeric keys are assigned. When working with associative arrays, setting `preserve_keys` to `true` is often preferred to retain data context.

Need help integrating this into your project?

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

Hire DigitalCodeLabs