OneBite.Dev - Coding blog in a bite size

Split An Array Into Smaller Arrays In PHP

Code snippet for how to Split An Array Into Smaller Arrays In PHP with sample and detail explanation

Manipulating arrays is an indispensable part of operations in most, if not all, programming languages. In PHP, one common operation is the splitting of an array into smaller subsections. This article provides step-by-step instructions on how to accomplish this task using PHP.

Code Snippet to Split an Array into Smaller Arrays in PHP

Here’s a simple way to divide an array into smaller chunks in PHP using the array_chunk function.

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
$smallerArrays = array_chunk($data, 2);
print_r($smallerArrays);

Code Explanation for Splitting an Array into Smaller Arrays

Let’s break down the code step-by-step to understand its functionality.

Firstly, we create a simple array named $data of 10 elements, ranging from 1 to 10.

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

Next, we use the function array_chunk. This function splits our $data array into smaller arrays. The size of these smaller arrays is defined by the second parameter. In our case, we set it to 2.

$smallerArrays = array_chunk($data, 2);

Here, array_chunk($data, 2) will split the $data into smaller arrays, each containing 2 elements from the original array.

This yields the result:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )
    [1] => Array
        (
            [0] => 3
            [1] => 4
        )
    [2] => Array
        (
            [0] => 5
            [1] => 6
        )
    [3] => Array
        (
            [0] => 7
            [1] => 8
        )
    [4] => Array
        (
            [0] => 9
            [1] => 10
        )
)

Finally, we use the print_r() function to display the $smallerArrays variable, which now holds the smaller arrays resulting from the array_chunk operation.

print_r($smallerArrays);

By utilizing the array_chunk function and understanding its application, you can seamlessly manipulate larger data sets into smaller, more manageable portions with PHP.

php