Laravel 5 Collections: Breaking a Collection Into a Specified Number of Groups With split

April 22, 2018 —John Koster

The split method is similar to the chunk method in that it used to break a collection into a smaller number of collections. However, when using the split method, you specify the number of groups you would like the collection split into and it will do its best to chunk the collection into the desired number of groups, with items distributed evenly.

If there are no items in the collection, a new, empty collection instance will be returned.


1public function split(
2 $numberOfGroups

#Example Use

We will use the sample array we created in the chunk method section:

1$testArray = [
2 'one' => '1',
3 'two' => '2',
4 'three' => '3',
5 'four' => '4',
6 'five' => '5',
7 'six' => '6'

As you can see, we have six elements in our $testArray. We will create a new collection and then split the collection into two groups:

1// Create the collection.
2$collection = collect($testArray);
4// Split the collection into two groups.
5$groups = $collection->split(2);

After the above code has executed, the $groups variable will contain a new collection instance containing two other collection instances as its items; both of these inner collections will contain elements from the original collection we split. The values of these inner collections would be:

First Inner Collection:

Index Value
one 1
two 2
three 3

Second Inner Collection:

Index Value
four 4
five 5
six 6

Some absolutely amazing

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.