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

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

Laravel 5

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 it's 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

public function split(
    $numberOfGroups
);

Example Use

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

$testArray = [
    'one'   => '1',
    'two'   => '2',
    'three' => '3',
    'four'  => '4',
    'five'  => '5',
    '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:

// Create the collection.
$collection = collect($testArray);

// Split the collection into two groups.
$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 it's 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

Start the Discussion

Leave a comment

Subscribe to our newsletter