2

Let's say I have an arbitrary array of keys:

$keys = array('foo', 'bar', 'baaz');

I'd like to use that array of keys to traverse a multidimensional array $values such that each element in the $keys array is one level of the $values array. For example, given the $keys array above, I'm looking for the equivalent of:

$values['foo']['bar']['baaz']

or:

$values[$keys[0]][$keys[1]][$keys[2]]

But I won't know what's in the $keys array or how large it is, so I couldn't hard code it like this.

Is there an elegant way to do this?

1 Answer 1

3
$value = $values;
foreach ($keys as $key) {
    $value = $value[$key];
}
echo $value;
Sign up to request clarification or add additional context in comments.

1 Comment

facepalm of course! And if I wanted to use it for assignment, it should be as simple as adding a reference operator to $value[$key], right?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.