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.
public function split( $numberOfGroups );
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:
Second Inner Collection: