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 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:
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 13 1 => int 24 2 => int 35 3 => int 46 4 => int 57 5 => int 68 6 => int 79 7 => int 8
∎
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.