Is there any way of referencing the entire key path in a single variable?
1) In a way like this: $fruits[$variable]
, the answer is no, there isn't.
Of course, there are several ways you can split a single $variable in two or more, and then use its parts separetely ($fruits[$part1][$part2]
)
This is a generic solution:
function get_path($array, $path)
{
$value = $array;
$parts = explode("']['", trim($path, "[']"));
foreach($parts as $key)
{
$value = $value[$key];
}
return $value;
}
$fruits['apple']['name'] = 'macintosh';
$path = "['apple']['name']";
echo get_path($fruits, $path);
// output = 'macintosh'
2) As also pointed, you could use "eval", which is not recommended:
$fruits['apple']['name'] = 'macintosh';
$path = "['apple']['name']";
eval('echo $fruits' . $path . ';');
// output = 'macintosh'
3) Finally, if you want to access an element of the array using a reference variable, then simply:
$fruits['apple']['name'] = 'macintosh';
$path &= $fruits['apple']['name'];
echo $path; // output = 'macintosh'
$path = 'MSX';
echo $fruits['apple']['name']; // output = 'MSX'