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;}
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)
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse