Let’s say I have the following multi-dimensional array:
$fruits['apple']['name'] = 'macintosh';
Is there any way of referencing the entire key path in a single variable?
I would like to somehow do the following:
$path = "['apple']['name']";
echo $fruits[$path];
//output would be "macintosh"
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:
2) As also pointed, you could use “eval”, which is not recommended:
3) Finally, if you want to access an element of the array using a reference variable, then simply: