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));

preferences:
36.67 ms | 402 KiB | 5 Q