PHP: How to split an array into chunks

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

Working with arrays is a fundamental part of PHP programming. There are instances when you need to divide a large array into smaller chunks for easier handling and processing. PHP provides a built-in function to achieve this, and this article discusses various methods to split an array into chunks with practical code examples.

Getting Started with array_chunk

The array_chunk function is the primary tool for splitting an array into chunks of smaller arrays. The function takes two mandatory parameters: the input array and the size of each chunk. Here’s a simple example:

$inputArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$chunks = array_chunk($inputArray, 2);
print_r($chunks);

Output:

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

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

    // So on ...
)

Preserving Original Keys

By default, array_chunk reindexes each chunk starting from zero. However, you can preserve the original array keys by passing a third optional boolean parameter as true.

$inputArray = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4];
$chunksWithKeys = array_chunk($inputArray, 2, true);
print_r($chunksWithKeys);

Output:

Array
(
    [0] => Array
        (
            [a] => 1
            [b] => 2
        )

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

Handling Arrays with Uneven Chunks

Sometimes the number of elements in an array doesn’t divide evenly. array_chunk will handle this gracefully, and the last chunk may be smaller than the specified size.

// Input array with 10 elements
$chunksUneven = array_chunk($inputArray, 3);
print_r($chunksUneven);

Output:

Array
(
    [0] => Array
        (
            // First 3 elements
        )

    [1] => Array
        (
           // Next 3 elements
        )

    [2] => Array
        (
           // Remaining 4 elements
        )
)

Using array_chunk with Multidimensional Arrays

array_chunk can also be used with multidimensional arrays, though it will only create chunks along the top-level elements:

$multiArray = [
    ['id' => 1, 'name' => 'Alice'],
    ['id' => 2, 'name' => 'Bob'],
    // ... more elements ...
];
$multiChunks = array_chunk($multiArray, 2);
print_r($multiChunks);

Output:

Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Alice
                )

            [1] => Array
                (
                    [id] => 2
                    [name] => Bob
                )

        )

    // Subsequent chunks
)

Advanced Usage: array_chunk in Custom Functions

When working with complex applications, we might wrap array_chunk within our custom functions to suit our special needs. Here’s an example of using array_chunk inside a function that distributes array elements evenly:

function evenlyDistributeArray($array, $numOfChunks) {
    $chunkSize = ceil(count($array) / $numOfChunks);
    return array_chunk($array, $chunkSize);
}

// Example usage
$result = evenlyDistributeArray([1, 2, 3, 4, 5, 6, 7, 8, 9], 4);
print_r($result);

Optimizing Performance with Large Arrays

When dealing with very large arrays, performance considerations become important. It can be optimized by minimizing the use of array_chunk within loops or recursive functions. Alternatively, using generators can be more memory-efficient.

Conclusion

PHP’s array_chunk is an invaluable function for splitting arrays into chunks. Whether you’re a beginner just learning the ropes or an advanced user looking for ways to handle large datasets, this function offers flexibility and ease of use for your array manipulation tasks. Remember to consider the performance of your application, especially when working with large arrays, and test thoroughly to ensure desired outcomes.