Laravel 5: Collapsing a Multi-Dimensional Array to a Single Level With collapse

April 11, 2018 —John Koster

The collapse helper method accepts an array as its only parameter. The given $array can be a single array, or a nested array. The method will then return a new array with the contents of all the nested arrays. Arrays that are collapsed can contain any data type, such as integers, string literals, objects and other arrays.

#Signature

The signature of the collapse method is:

1public static function collapse(
2 $array
3);

#Example Use

The examples that follow will use integers in all arrays. Assuming the following array and example:

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

The value of $collapsedArray would then be:

1array
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

It is important to note that the collapse method is not recursive. This can be observed in the following example:

1use \Illuminate\Support\Arr;
2 
3$testArray = [
4 [
5 1,2,3,4
6 ],
7 [
8 5,6,7,8,
9 [
10 9,10,11,12
11 ]
12 ]
13];
14 
15$collapsedArray = Arr::collapse($testArray);

The value of $collapsedArray would then have the value:

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

#Collapsing Collections

The collapse method will also work on collections. There is no special syntax required to use collections with the collapse method:

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

The value of $collapsedArray would then be:

1array
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:

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

The value of collapsed array would then be:

1array
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

#Global array_collapse Helper Function

The array_collapse function is a shortcut to calling Arr::collapse. This function is declared in the global namespace.

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.