Firstly, do not use string
for $indexes
, use an array
.
For simple retrieving, you can use array_reduce
:
$result = array_reduce($indexes, function ($array, $index) {
return isset($array[$index]) ? $array[$index] : null;
}, $array);
Note that value defaults to null
when there is no such index in the array.
Here is working demo.
If you want some more sophisticated stuff, check out a library I wrote some time ago for situations, when you also need to add items to an array and check for the existence:
var_dump(isset($array[['foo', 'bar']]));
var_dump($array[['foo', 'bar']]);
$array[['foo', 'bar']] = 'baz';
unset($array[['foo', 'bar']]);
They are all valid usage examples for existence checking, retrieving the element, writing the element and deleting the element respectively.