Search

Laravel Array Helper Function: array_collapse

November 18, 2016 —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 examples that follow will use integers in all arrays.

Assuming the following array and example:

1<?php
2 
3use \Illuminate\Support\Arr;
4 
5$testArray = [
6 [
7 1,2,3,4
8 ],
9 [
10 5,6,7,8,
11 ]
12];
13 
14$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

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

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

The value of $collapsedArray would then have the value:

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

#array_collapse($array)

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.