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);
Output for 7.4.0 - 7.4.33, 8.0.1 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.27, 8.4.1 - 8.4.14
Path attempt failed for [1][children][0][children][0][country][city]. No `children` key found on levelIndex 3 --- array ( '0,0,0' => 'Paris', '1,0' => 'New York', )

preferences:
141.06 ms | 407 KiB | 5 Q