user113292
user113292

Reputation:

How can I traverse a multidimensional array using an array of keys?

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?

Upvotes: 2

Views: 72

Answers (1)

deceze
deceze

Reputation: 522606

$value = $values;
foreach ($keys as $key) {
    $value = $value[$key];
}
echo $value;

Upvotes: 3

Related Questions