0

I want to find a way to set a value in a multi-dimensional array with a dynamic subscript. Let me illustrate a very simple example:

$deep['foo'] = array();
$deep['foo']['bar'] = "Elvis has left the building";
$meta = array( 'foo','bar' );
$super_meta = "[{$meta[0]}][{$meta[1]}]";
echo "\nWhere is Elvis? " . $deep[$meta[0]][$meta[1]] . ". Are we sure?\n";
echo "\nWhere is Elvis? " . $deep{$super_meta} . ".\n\n";

In this example the first echo line prints Elvis has left the building as we'd expect but in the second echo line, we don't know until runtime how many levels deep in the $meta structure we are going to go. In a desperate attempt to make my dreams come true I've added the $deep{$super_meta} command. No errors but it results in an empty string. Darn.

With my dreams crushed I'm hoping someone can pick me back up again and show me the proverbial "PHP light".

2
  • If I understand this, you want to be able to set $meta to an array with any number of elements, and extract the value from $deep that follows the "path" defined in $meta, is that right? Commented Feb 5, 2013 at 15:22
  • @leftclickben, yes that is correct Commented Feb 5, 2013 at 15:28

1 Answer 1

1

You need to start with the whole array ($deep), then iterate through the elements in $meta and for each one, extract a deeper nested array. Try this:

$result = $deep;
foreach ($meta as $elem) {
    $result = $result[$elem];
}
echo $result;
// outputs "Elvis has left the building"

Note that this does not include any error checking. It will return with a big fat error if any element does not exist. You can handle this quite easily:

$result = $deep;
foreach ($meta as $elem) {
    if (array_key_exists($elem, $result)) {
        $result = $result[$elem];
    } else {
        // Handle error in some way, maybe throw an exception
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes I had a feeling someone was going suggest recursion. My left-brain has had a tragic accident that makes me flinch whenever the word recursion is used but this should work for my purposes.
You don't need recursion for this, just iteration as per my answer. In general, if you know in advance how many times you need to do something, then use iteration. If you don't know how many times, but you know what the end condition is, use recursion. In this case, you have as your input the $meta array, which means you know how many times to repeat, so use iteration. About it being a "singular statement" by which I assume you mean a one-liner, wrap my code in a function (which throws an exception where I indicated) and you have a one-liner that can be wrapped in a try-catch block.

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.