April 11, 2018 —John Koster
The flatten
helper method is similar to the dot
method in that it takes a multi-dimensional array and transforms it into a new array with only one dimension. While the dot
method preserves the keys by separating them with dots
, the flatten
method will create a new array containing the original array's data whilst throwing away the array's keys.
This method will recursively flatten an array, the maximum number of sub-arrays to traverse can be controlled using the $depth
parameter.
The signature of the flatten
method is:
1public static function flatten(2 $array,3 $depth = INF4);
Consider the following array:
1$arrayToFlatten = [2 'keys' => 'first value',3 'will' => 'second value',4 'be' => 'third value',5 'removed' => 'fourth value'6];
If we flatten the array like so:
1<?php2 3$newArray = Arr::flatten(4 $arrayToFlatten5 );
the resulting array would be:
1array {2 "first value"3 "second value"4 "third value"5 "fourth value"6}
array_flatten
Helper FunctionThe array_flatten
function is a shortcut to calling Arr::flatten
. 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.