Sling Academy
Home/PHP/PHP: How to split an array into chunks

PHP: How to split an array into chunks

Last updated: January 10, 2024

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.

Next Article: Reducing Arrays in PHP: A Practical Guide

Previous Article: How to check if an array contains a value in PHP

Series: PHP Data Structure Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array