0

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.

4 Answers 4

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

wow, i dunno how you whipped that up so fast, but thanks dude. exactly what i was looking for.
2

You could try with RecursiveArrayIterator

Here is an example on how to use it.

1 Comment

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

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.

3 Comments

your non-recursive one works about the same way as the chosen one above. thanks though. i appreciate it!
@onassar: But using array_key_exists is more safe since empty returns true for values like "", null, false, array(), 0 and "0".
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!
1

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

Won't this do?

1 Comment

couldn't do that as i didn't want to explicitly write access to the value, since it could vary. thanks though!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.