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

2 min read

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.

Signature

1public function split(
2 $numberOfGroups
3);

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'
8];

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);
3 
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

Thanks for taking the time to read this post! If you found this article useful and want to help support more work like this, please consider sponsoring my work on GitHub, or by checking out some merch.

 Sponsor on GitHub  Shop Merch