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”.
You need to start with the whole array (
$deep), then iterate through the elements in$metaand for each one, extract a deeper nested array. Try this: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: