How to Split Array Into Chunks or Parts in PHP

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.

Output

Array ( [0] => Array ( [0] => Cycle [1] => Bike ) [1] => Array ( [0] => Car [1] => Bolero ) [2] => Array ( [0] => BMW [1] => WagonR ) [3] => Array ( [0] => Maruti ) )

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.

Output

Array ( [0] => Array ( [0] => Cycle [1] => Bike [2] => Car ) [1] => Array ( [0] => Bolero [1] => BMW [2] => WagonR ) [2] => Array ( [0] => Maruti ) )

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.

Output

Array ( [0] => Array ( [0] => Cycle [1] => Bike [2] => Car [3] => Bolero ) [1] => Array ( [0] => BMW [1] => WagonR [2] => Maruti ) )

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.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.