During development, the developer needs to go through loops to prepare a single dimensional array out of a multi-dimensional array.
Laravel provides many helpers which come handy in multiple ways and saves developers work.
One of such is
Arr::flatten() which flattens a multi-dimensional array into a single level by default.
Tested with Laravel versions 5.8, 6 and 7.
We need to import
Illuminate\Support\Arr namespace with
Kindly check for your version on the official DOC for Laravel Helper Arr::flatten(). This link will take you to Laravel 7 Documentation.
Arr::flatten(array $array, [int $depth = INF])
- The first parameter is necessary and must be an array that needs to be flattened.
- Laravel will extract elements and provides us with a new single dimension array based on the depth parameter.
- The second parameter specifies the depth and it's an optional parameter.
- This value must be an integer type.
- The depth specifies how deep a nested array should be flattened.
- The default value for depth is infinity(
INF) from which Laravel will extract elements and provides us with a new single dimension array.
It returns a new 1-D flattened array.
$data = [ 'country' => 'India 🇮🇳', 'languages' => [ 'Gujarati', 'Hindi', 'Sanskrit', 'Tamil', 'Urdu', ], ]; dd( Arr::flatten($data) );
array:3 [ 0 => "India 🇮🇳" 1 => "Gujarati" 2 => "Hindi" 3 => "Sanskrit" 4 => "Tamil" 5 => "Urdu" ]
Read others post on our site MeshWorld
- Laravel Arr flatten method documentation
Happy 😄 coding
With ❤️ from 🇮🇳