3v4l.org

run code in 300+ PHP versions simultaneously
<?php $arr = array( 'key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3', 'key4' => array( 'subkey1' => 'subval1', 'subkey2' => 'subval2', ) ); function walkArray($input) { // Define our output array $output = array( 'keys' => '', 'vals' => '', 'children' => array(), ); // We're looping trough the input array foreach($input AS $key => $value) { // If the current value is an array we reached the next dimension if(is_array($value)) { // So we call walkArray() recursively with our current value // and assign the returned array to a new element in our $output's 'children' key $output['children'][] = walkArray($value); } else { // We'll concatenate our keys and values... $output['keys'] .= $key . ', '; $output['vals'] .= ':' . $value .', '; } } // And get rid of the trailing commas $output['keys'] = rtrim($output['keys'], ', '); $output['vals'] = rtrim($output['vals'], ', '); // Eventually we return our output array return $output; } ?> print_r(walkArray($arr));
Output for 4.3.0 - 4.3.11, 4.4.0 - 4.4.9, 5.0.0 - 5.0.5, 5.1.0 - 5.1.6, 5.2.0 - 5.2.17, 5.3.0 - 5.3.29, 5.4.0 - 5.4.45, 5.5.24 - 5.5.35, 5.6.7 - 5.6.28, 7.0.0 - 7.0.20, 7.1.0 - 7.1.7, 7.2.29 - 7.2.33, 7.3.16 - 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
print_r(walkArray($arr));

preferences:
217.48 ms | 406 KiB | 309 Q