3

I'm trying to figure out how I can use the values an indexed array as path for another array. I'm exploding a string to an array, and based on all values in that array I'm looking for a value in another array.

Example:

$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my@string@is@nested';
$items = explode('@', $var);

// .. echo $haystack[... items..?]

The number of values may differ, so it's not an option to do just $haystack[$items[0][$items[1][$items[2][$items[3]].

Any suggestions?

3 Answers 3

2

You can use a loop -

$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my@string@is@nested';
$items = explode('@', $var);

$temp = $haystack;
foreach($items as $v) {
    $temp = $temp[$v]; // Store the current array value
}
echo $temp;

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for helping me out. Works like a charm. +1 and accepted.
2

You can use a loop to grab each subsequent nested array. I.e:

$haystack['my']['string']['is']['nested'] = 'Hello';
$var = 'my@string@is@nested';
$items = explode('@', $var);
$val = $haystack;
foreach($items as $key){
    $val = $val[$key];
}
echo $val;

Note that this does no checking, you likely want to check that $val[$key] exists.

Example here: http://codepad.org/5ei9xS91

3 Comments

Thanks for helping me out. Works like a charm, neat solution. @b0s3 was just a bit earlier. Can only accept one answer. +1
@ben Nope first answer was posted by Jim
Strange, my browser is telling me otherwise ;) Nonetheless, thanks :)
2

Or you can use a recursive function:

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

$haystack = array('my' => array('string' => array('is' => array('nested' => 'hello'))));
echo extractValue($haystack, explode('@', 'my@string@is@nested'));

1 Comment

Thanks for taking time to respond. A working solution has been provided, while yours works too. Have a nice day. +1

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.