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.
The signature of the collapse method is:
1public static function collapse(2 $array3);
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:
1array2 0 => int 13 1 => int 24 2 => int 35 3 => int 46 4 => int 57 5 => int 68 6 => int 79 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,1211 ]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 810 8 =>11 array12 0 => int 913 1 => int 1014 2 => int 1115 3 => int 12
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:
1array2 0 => int 13 1 => int 24 2 => int 35 3 => int 46 4 => int 57 5 => int 68 6 => int 79 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:
1array2 0 => int 13 1 => int 24 2 => int 35 3 => int 46 4 => int 57 5 => int 68 6 => int 79 7 => int 8
array_collapse
Helper FunctionThe array_collapse
function is a shortcut to calling Arr::collapse
. This function is declared in the global namespace.
∎
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.