3v4l.org

run code in 300+ PHP versions simultaneously
<?php function flatten($array, $prefix = '') { $return = []; foreach ($array as $key => $value) { if (is_array($value)) { $return = array_merge($return, flatten($value, $prefix . $key . '_')); } else { $return[$prefix . $key] = $value; } } return $return; } // proof that it's working on the simple cases var_dump(flatten([ 1, 2, 3 => [4, 5] ])); var_dump(flatten([ [1, 2], [3, 4] ])); // use array_values on the result if you don't care about keys // simple multidimensional array var_dump(flatten([ 'a' => [ 'b' => 'value', ] ])); // proof that it's not overwriting values like all the other solutions var_dump(flatten([ 'a' => [ 'b' => 'value', ], 'c' => [ 'b' => 'anothervalue', ], ]));
Output for 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.4, 8.3.6
array(4) { [0]=> int(1) [1]=> int(2) ["3_0"]=> int(4) ["3_1"]=> int(5) } array(4) { ["0_0"]=> int(1) ["0_1"]=> int(2) ["1_0"]=> int(3) ["1_1"]=> int(4) } array(1) { ["a_b"]=> string(5) "value" } array(2) { ["a_b"]=> string(5) "value" ["c_b"]=> string(12) "anothervalue" }
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 array(4) { [0]=> int(1) [1]=> int(2) ["3_0"]=> int(4) ["3_1"]=> int(5) } array(4) { ["0_0"]=> int(1) ["0_1"]=> int(2) ["1_0"]=> int(3) ["1_1"]=> int(4) } array(1) { ["a_b"]=> string(5) "value" } array(2) { ["a_b"]=> string(5) "value" ["c_b"]=> string(12) "anothervalue" }

preferences:
159.73 ms | 402 KiB | 191 Q