3v4l.org

run code in 300+ PHP versions simultaneously
<?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.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
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, )

preferences:
261.48 ms | 405 KiB | 385 Q