3v4l.org

run code in 300+ PHP versions simultaneously
<?php $testArray = [ ['lev 1' => 'lev 1'], ['lev 2', 'lev 2 - 1', ['lev 2 - 2'], ['Key preserved' => 'lev 2 - 3']], [['lev 3 - 1', 'lev 3 - 2', 'lev 3 - 3']], [[[888 => 'lev 4']]] ]; // $element must initially be an array. Anything that is not an array will just return the accumulator. function flatten($element, $accum = []) { // If we don't have an array return the accumulator. if (!is_array($element)) { return $accum; } foreach($element as $key => $e) { // Check if the elements are an array or not. If not, append the accumulator with a key and value. if (!is_array($e)) { // Check that the key does not already exist, if it does we have to simply append to preserve values. if (array_key_exists($key, $accum)) { $accum[] = $e; } else { $accum[$key] = $e; } } // Only recurse when we have an array. if (is_array($e)) { // We pass in the accumulator and any values further down then hierachy. $vals = flatten($e, $accum); // We might get an empty array back if there was an array of arrays. if (!empty($vals)) { // We don't append our values here, we override the accumulator. The appending happens above when $e is not an // array. $accum = $vals; } } } // Return values of this array and all child arrays. return $accum; } var_dump(flatten($testArray));
Output for git.master, git.master_jit, rfc.property-hooks
array(9) { ["lev 1"]=> string(5) "lev 1" [0]=> string(5) "lev 2" [1]=> string(9) "lev 2 - 1" [2]=> string(9) "lev 2 - 2" ["Key preserved"]=> string(9) "lev 2 - 3" [3]=> string(9) "lev 3 - 1" [4]=> string(9) "lev 3 - 2" [5]=> string(9) "lev 3 - 3" [888]=> string(5) "lev 4" }

This tab shows result from various feature-branches currently under review by the php developers. Contact me to have additional branches featured.

Active branches

Archived branches

Once feature-branches are merged or declined, they are no longer available. Their functionality (when merged) can be viewed from the main output page


preferences:
25.38 ms | 406 KiB | 5 Q