April 22, 2018 —John Koster
The collapse
method combines all the first-level items of a collection into a new, single collection. The returned value of the collapse
method is an instance of the Collection
class.
1public function collapse();
We will create a simple collection to work with like this:
1use Illuminate\Support\Collection; 2 3$first = [ 4 0, 1, 2, 3, 4 5]; 6 7$second = [ 8 5, 6, 7, 8 , 9 9];10 11$collection = new Collection([$first, $second]);
The $collection
variable now has an internal structure similar to the following output:
1object(Illuminate\Support\Collection) 2 protected 'items' => 3 array 4 0 => 5 array 6 0 => int 0 7 1 => int 1 8 2 => int 2 9 3 => int 310 4 => int 411 1 =>12 array13 0 => int 514 1 => int 615 2 => int 716 3 => int 817 4 => int 9
We can see that our collection contains two arrays. Using the collapse
method, we can get a Collection
instance that combines the two arrays above:
1$collapsed = $collection->collapse();
Now, the $collapsed
variable would have a value similar to the following:
1object(Illuminate\Support\Collection) 2 protected 'items' => 3 array 4 0 => int 0 5 1 => int 1 6 2 => int 2 7 3 => int 3 8 4 => int 4 9 5 => int 510 6 => int 611 7 => int 712 8 => int 813 9 => int 9
The collapse
method internally calls the Illuminate\Support\Arr::collapse($array)
helper function. It will collapse both nested arrays and Collection
instances.
It should be noted that the collapse
method does not recursively collapse inner arrays. The following code sample will create another collection, this time with a nested array:
1use Illuminate\Support\Collection; 2 3$first = [ 4 0, 1, 2, 3, 4 5]; 6 7$second = [ 8 [5, 6, 7, 8 , 9] 9];10 11$collection = new Collection([$first, $second]);
If we collapsed the $collection
, the result would be similar to the following output:
1object(Illuminate\Support\Collection) 2 protected 'items' => 3 array 4 0 => int 0 5 1 => int 1 6 2 => int 2 7 3 => int 3 8 4 => int 4 9 5 =>10 array11 0 => int 512 1 => int 613 2 => int 714 3 => int 815 4 => int 9
∎
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.