3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php function flatten_array($array, $preserve_keys = 0, &$out = array()) { # Flatten a multidimensional array to one dimension, optionally preserving keys. # # $array - the array to flatten # $preserve_keys - 0 (default) to not preserve keys, 1 to preserve string keys only, 2 to preserve all keys # $out - internal use argument for recursion foreach($array as $key => $child) if(is_array($child)) $out = flatten_array($child, $preserve_keys, $out); elseif($preserve_keys + is_string($key) > 1) $out[$key] = $child; else $out[] = $child; return $out; } $array = array( 'first' => 1, 'second' => 2, 'query' => array( 'id' => 314, 'descripcion' => 'Test', 'files' => array( array( 'name' => 'Readme.txt', 'path' => '/tmp/43143431431343', ), array( 'name' => 'Picture.jpg', 'path' => '/tmp/98794894594655', ), ), ), 'last' => 99, ); echo "Original:\n"; var_export($array); echo "\n\nFlat:\n"; var_export( flatten_array($array, 1) );
Output for 5.3.18 - 5.6.38, hhvm-3.10.1 - 3.22.0, 7.0.0 - 7.2.10
Original: array ( 'first' => 1, 'second' => 2, 'query' => array ( 'id' => 314, 'descripcion' => 'Test', 'files' => array ( 0 => array ( 'name' => 'Readme.txt', 'path' => '/tmp/43143431431343', ), 1 => array ( 'name' => 'Picture.jpg', 'path' => '/tmp/98794894594655', ), ), ), 'last' => 99, ) Flat: array ( 'first' => 1, 'second' => 2, 'id' => 314, 'descripcion' => 'Test', 'name' => 'Picture.jpg', 'path' => '/tmp/98794894594655', 'last' => 99, )