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?

3 Answers 3

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"
Sign up to request clarification or add additional context in comments.

6 Comments

If I could think of another solution to the problem, I would gladly take it!
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.
I updated my code above to use return IMHO it's the best of the worst
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.
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.
|
0

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

Comments

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.

1 Comment

In this specific case, array's are not an approiate solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.