0

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?

YsoL8
  • 2,186
  • 5
  • 29
  • 47

3 Answers3

1

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"
xzyfer
  • 13,937
  • 5
  • 35
  • 46
  • If I could think of another solution to the problem, I would gladly take it! – YsoL8 Feb 21 '11 at 11:28
  • Could you describe the problem a little more. A community of developers is a great place to get some advice and possibly re-evaluate a better solution. – xzyfer Feb 21 '11 at 11:30
  • I updated my code above to use `return` IMHO it's the best of the worst – xzyfer Feb 21 '11 at 11:38
  • Basically, I am taking a variable name stored in the database, and if it exists in the code, appending the value and processing it. It is part of a generic form object and brings in a stored defualt. Because of the various scope limits on the site, I can't predict which array I will be attempting to access, so I use the stored name as a variable variable to cover all possibilities. – YsoL8 Feb 21 '11 at 11:39
  • It's too broad of an issue for any specific help. Take what you can get I guess. That's the best I got. Hope it helps. – xzyfer Feb 21 '11 at 11:44
  • @ xzyfer I asked the OP not one based on what I wrote for that reason. Also I have your solution 90% intergrated now, so cheers for the good help in a bad situation. – YsoL8 Feb 21 '11 at 11:49
0

$foo[$key_var] should work, unless I misunderstood your question?

Shadikka
  • 4,116
  • 2
  • 16
  • 19
0

No, I don't think this is possible. The only thing (obviously) possible is to use a variable index, and access $foo[$bar].

However, using variable variables is usually very bad practice anyway - especially because they make debugging and automatic documentation / variable lookup so terribly difficult. It's usually best not to use them, but to use an array instead.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088