Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Flatten Array using Arr::flatten() in Laravel
Vishnu Damwala
Vishnu Damwala

Posted on • Originally published atmeshworld.in

     

Flatten Array using Arr::flatten() in Laravel

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 isArr::flatten() which flattens a multi-dimensional array into a single level by default.

Tested with Laravel versions5.8,6 and7.

We need to importIlluminate\Support\Arr namespace withuse keyword.

Kindly check for your version on the official DOC forLaravel Helper Arr::flatten(). This link will take you toLaravel 7 Documentation.

Syntax

Arr::flatten(array$array,[int$depth=INF])

Parameters

\$array (necessary)

  • The first parameter is necessary and must be anarray that needs to be flattened.
  • Laravel will extract elements and provides us with a new single dimension array based on the depth parameter.

\$depth (optional)

  • 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.

Return value

It returns a new 1-D flattened array.

Example

$data=['country'=>'India 🇮🇳','languages'=>['Gujarati','Hindi','Sanskrit','Tamil','Urdu',],];dd(Arr::flatten($data));

Output

array:3 [  0 => "India 🇮🇳"  1 => "Gujarati"  2 => "Hindi"  3 => "Sanskrit"  4 => "Tamil"  5 => "Urdu"]

Read the complete post on our siteMeshWorld  - Flatten Array using Arr::flatten() in Laravel

Read others post on our siteMeshWorld

Resources

  • Laravel Arr flatten method documentation

Happy 😄 coding
With ❤️ from 🇮🇳

Top comments(1)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
goatsedolan profile image
Goatse Dolan Duck
  • Joined

I also like to usearray_merge(... $array) when I need to preserve keys.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A human being currently living in India🇮🇳 on Earth.Founder of MeshWorld, a web geek, an industry experienced web developer & tutor/instructor currently lives in Surat City.
  • Location
    Surat, India
  • Joined

More fromVishnu Damwala

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp