Search

Laravel 5: Reducing a Multi-Dimensional Array to a Single Dimension Losing Keys With flatten

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.

#Signature Use

The signature of the flatten method is:

1public static function flatten(
2 $array,
3 $depth = INF
4);

#Example Use

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<?php
2 
3$newArray = Arr::flatten(
4 $arrayToFlatten
5 );

the resulting array would be:

1array {
2 "first value"
3 "second value"
4 "third value"
5 "fourth value"
6}

#Global array_flatten Helper Function

The array_flatten function is a shortcut to calling Arr::flatten. 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.