Last Updated on July 28, 2021 by Roshan Parihar
In this tutorial, learn how to split array into chunks of 2, 3, or 4 in PHP. The short answer is to use the array_chunk()
function that takes two arguments to break the array into parts.
You can specify the number of chunks you want to create from the given array in PHP. Let’s find out with the different examples given below with output.
How to Split Array into Chunks of Two in PHP
To split the array into chunks of two, you have to use the array_chunk()
function and pass 2 as its second argument. The first argument is the given that you have to split into chunks.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare an array in PHP $myarray = array("Cycle", "Bike", "Car", "Bolero", "BMW", "WagonR", "Maruti"); //Split into chunks of 2 $myArrChunks = array_chunk($myarray, 2); //Print result print_r($myArrChunks); ?> |
Output
There are seven elements in an array. When you use the array_chunk()
function for splitting, it create sub-array in which each array contains 2 elements.
Break Array into Parts of Three in PHP
When you have to break the array into parts, you have to use the array_chunk()
function with two arguments. Pass the array variable as the first argument and the number of chunks as 3 in the second argument.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare an array in PHP $myarray = array("Cycle", "Bike", "Car", "Bolero", "BMW", "WagonR", "Maruti"); //Break in chunks of 3 $myArrChunks = array_chunk($myarray, 3); //Print result print_r($myArrChunks); ?> |
Output
The above example shows the given array into 3 parts. The first and parts contain 3 elements. However, the last element contains only a single element after breaking the array into parts in PHP.
Split into Chunks of Four Using PHP
In addition to the above methods, you can also split the array into chunks of four in PHP. You have to just pass 4 as the second argument of the array_chunk()
function as given below.
1 2 3 4 5 6 7 8 9 10 |
<?php //Declare an array in PHP $myarray = array("Cycle", "Bike", "Car", "Bolero", "BMW", "WagonR", "Maruti"); //Split into chunks of 4 $myArrChunks = array_chunk($myarray, 4); //Print result print_r($myArrChunks); ?> |
Output
After splitting the array into chunks of 4, the first array part contains 4 elements and the last array part contains 3 elements. This is because only 3 elements remain in the last array part in PHP.