views:

46

answers:

4

I have a unique case where I have an array like so:

$a = array('a' => array('b' => array('c' => 'woohoo!')));

I want to access values of the array in a manner like this:

  • some_function($a, array('a')) which would return the array for position a
  • some_function($a, array('a', 'b', 'c')) which would return the word 'woohoo'

So basically, it drills down in the array using the passed in variables in the second param and checks for the existence of that key in the result. Any ideas on some native php functions that can help do this? I'm assuming it'll need to make use of recursion. Any thoughts would be really appreciated.

Thanks.

+1  A: 

$a['a'] returns the array at position a.
$a['a']['b']['c'] returns woohoo.

Won't this do?

Tatu Ulmanen
couldn't do that as i didn't want to explicitly write access to the value, since it could vary. thanks though!
onassar
+2  A: 

Here’s a recursive implementation:

function some_function($array, $path) {
    if (!count($path)) {
        return;
    }
    $key = array_shift($path);
    if (!array_key_exists($key, $array)) {
        return;
    }
    if (count($path) > 1) {
        return some_function($array[$key], $path);
    } else {
        return $array[$key];
    }
}

And an iterative implementation:

function some_function($array, $path) {
    if (!count($path)) {
        return;
    }
    $tmp = &$array;
    foreach ($path as $key) {
        if (!array_key_exists($key, $tmp)) {
            return;
        }
        $tmp = &$tmp[$key];
    }
    return $tmp;
}

These functions will return null if the path is not valid.

Gumbo
your non-recursive one works about the same way as the chosen one above. thanks though. i appreciate it!
onassar
@onassar: But using `array_key_exists` is more safe since `empty` returns *true* for values like `""`, *null*, *false*, `array()`, `0` and `"0"`.
Gumbo
true that! thanks sir. i've modified mine to make use of that. i bet that would bit me in the ass way down the line and resulted in hours of debugging :( thanks!
onassar
+2  A: 

You could try with RecursiveArrayIterator

Here is an example on how to use it.

Gordon
thanks for the tip, but the above one which doesn't use recursion is preferred. much easier to follow :)
onassar
+2  A: 

This is untested but you shouldn't need recursion to handle this case:

function getValueByKey($array, $key) {
    foreach ($key as $val) {
        if (!empty($array[$val])) {
            $array = $array[$val];
        } else return false;
    }
    return $array;
}
cballou
wow, i dunno how you whipped that up so fast, but thanks dude. exactly what i was looking for.
onassar