Search code examples
phpvariable-variables

can array values be accessed by variable variables?


I have an array which I can only access correctly via variable variables, like so:

$foo['bar'] = "pie";

$fixed_name_variable = "foo['bar']";

echo $$fixed_name_variable;

Which in theroy echo's pie. Except it's just not returning anything. So I need to know if this approach is actually workable or if I need a rethink on it.

Just noticed. On the second line, should the bar be in quotes?


Solution

  • Although I hate to encourage this behaviour, you can use eval to achieve what you to a limited extent.

    $foo['bar'] = "pie";
    $fixed_name_variable = "foo['bar']";
    
    $a = eval("return $$fixed_name_variable;"); 
    echo $a; //outputs "pie"