tomsseisums
tomsseisums

Reputation: 13367

How to get array value dynamically

I'm not sure if there is such a function, but I'd expect it to do the following: get_array_value($array, $chain); where $array is the array to search for the value, and $chain is an array that contains information which value to retrieve.

Example usage: if $chain = array('key1', 'key2', 'key3');, then the function should return $array['key1']['key2']['key3'];

Is there anything similar out there already and if not, how could I achieve this?

Thanks in advance!

UPDATE:

Huh, the intended result should be a single value, not an array. So I could use it like echo get_array_value($array, $chain);

Upvotes: 1

Views: 2343

Answers (2)

KingCrunch
KingCrunch

Reputation: 131901

function resolve ($array, $chain) {
    return empty($chain) 
        ? $array;
        :resolve($array[array_shift($chain)], $chain);
}

Thats the very short form. You must verify, that all keys, that you want to resolve, exists (and such).

Upvotes: 3

Gaurav
Gaurav

Reputation: 28755

$cloneArray = $array;  // clone it for future usage
foreach($chain as $value)
{
   $cloneArray =  $cloneArray[$value];
}

var_dump($cloneArray);

Upvotes: 5

Related Questions