Search

Laravel 5 Collections: Converting a Multi-Dimensional Collection Into a Single Dimension With collapse

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.

#Signature

1public function collapse();

#Example Use

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 3
10 4 => int 4
11 1 =>
12 array
13 0 => int 5
14 1 => int 6
15 2 => int 7
16 3 => int 8
17 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 5
10 6 => int 6
11 7 => int 7
12 8 => int 8
13 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 array
11 0 => int 5
12 1 => int 6
13 2 => int 7
14 3 => int 8
15 4 => int 9

Some absolutely amazing
people

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.