3v4l.org

run code in 300+ PHP versions simultaneously
<?php function getValue($haystack, $indexes) { $indices = explode(',', $indexes); $finalIndex = array_pop($indices); $keys = []; foreach ($indices as $keys[]) { $keys[] = 'children'; } array_push($keys, $finalIndex, 'country', 'city'); //var_export($keys); foreach ($keys as $level => $key) { if (!key_exists($key, $haystack)) { throw new Exception( sprintf( "Path attempt failed for [%s]. No `%s` key found on levelIndex %d", implode('][', $keys), $key, $level ) ); } $haystack = $haystack[$key]; } return $haystack; } $test = [ [ 'children' => [ [ 'children' => [ [ 'country' => [ 'city' => 'Paris', ] ], [ 'country' => [ 'city' => 'Kyiv', ] ] ] ] ] ], [ 'children' => [ [ 'country' => [ 'city' => 'New York', ] ], [ 'country' => [ 'city' => 'Sydney', ] ] ] ] ]; $result = []; try { $result['0,0,0'] = getValue($test, '0,0,0'); $result['1,0'] = getValue($test, '1,0'); $result['1,0,0'] = getValue($test, '1,0,0'); } catch (Exception $e) { echo $e->getMessage() . "\n---\n"; } var_export($result);

preferences:
27.81 ms | 410 KiB | 5 Q