Search

Collapsing Laravel Collections using array_collapse

November 18, 2016 —John Koster

This article is a continuation of the Laravel Array Helper Function: array_collapse article.

The collapse (defined in the Illuminate\Support\Arr helper class) method will also work on Illuminate collections. There is no special syntax required to use collections with the collapse method:

1<?php
2 
3use \Illuminate\Support\Arr;
4use \Illuminate\Support\Collection;
5 
6$testArray = [
7 new Collection([1,2,3,4]),
8 new Collection([5,6,7,8])
9];
10 
11$collapsedArray = Arr::collapse($testArray);

The value of $collapsedArray would then be:

1array (size=8)
2 0 => int 1
3 1 => int 2
4 2 => int 3
5 3 => int 4
6 4 => int 5
7 5 => int 6
8 6 => int 7
9 7 => int 8

Nested collections can also be collapsed:

1<?php
2 
3use \Illuminate\Support\Arr;
4use \Illuminate\Support\Collection;
5 
6$testArray = new Collection([
7 new Collection([1,2,3,4]),
8 [5,6,7,8]
9]);
10 
11$collapsedArray = Arr::collapse($testArray);

The value of collapsed array would then be:

1array (size=8)
2 0 => int 1
3 1 => int 2
4 2 => int 3
5 3 => int 4
6 4 => int 5
7 5 => int 6
8 6 => int 7
9 7 => int 8

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.