Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Paulund
Paulund

Posted on • Originally published atpaulund.co.uk

Flatten Nested Arrays With PHP

Here is a quick code snippet for flattening a multi-dimensional array using PHP.

This uses the functionarray_walk_recursive that applies a function to every element of an array. Using this function we can add the value to a new array and return that instance.

functionflatten(array$array){$return=array();array_walk_recursive($array,function($a)use(&$return){$return[]=$a;});return$return;}
Enter fullscreen modeExit fullscreen mode
print_r(flatten([1,2,[3],[4,[5,6],5,6],[[7],[8,[9]]],10,[[[11],12]]]));Array([0]=>1[1]=>2[2]=>3[3]=>4[4]=>5[5]=>6[6]=>5[7]=>6[8]=>7[9]=>8[10]=>9[11]=>10[12]=>11[13]=>12)
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

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

Dismiss

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

Full Stack Engineer I post about #Laravel #PHP and Software engineering on https://paulund.co.ukWorking on a website monitoring tool - https://upchecker.app
  • Location
    Bristol
  • Joined

More fromPaulund

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