0

I want to be able to pass a string ("['parent_array']['child_array']") to a function that then pulls this string and "my_array" to the front of it and then creates a variable variable.

Then inside the function i do print_r($$string) and nothing comes out. See the code below for a better explanation.

// DOES NOT WORK
$string1 = "my_array['parent_array']['child_array']";
print_r($$string1); //prints nothing.

// WORKS
$string2 = "test";
$test = "This will be printed!";
print_r($$string2); //prints "This will be printed!

// WORKS
print_r($my_array['parent_array']['child_array']);
5
  • 2
    May I ask why are you building the variables this way? I could bet a large sum of money for there being a more reasonable approach than (shudder) variable variables. Commented Mar 28, 2012 at 8:51
  • 2
    and / or eval, I bet one of the answers later would actually recommend to use eval Commented Mar 28, 2012 at 8:52
  • 2
    @andreas No sooner said than done... Commented Mar 28, 2012 at 8:54
  • Read this stackoverflow.com/questions/2036547/… Commented Mar 28, 2012 at 9:13
  • 2
    You seem to be asking for a bugfix of a patch from solution to a problem. That not the way to go. Instead you should describe the problem, show how you tried to sole it and ask for better solution or changes for the existing one. Commented Mar 28, 2012 at 9:54

1 Answer 1

0

Variable variables are an ugly, ugly hack.

Use eval.

Example:

$expr = "\$my_array['parent_array']['child_array']";
$val = 'not assigned';
eval("\$val = $expr;");
print_r($val);

But please follow their warnings about the danger of evaling user-supplied code.

Updated: with example

Sign up to request clarification or add additional context in comments.

8 Comments

Can I get a example how this would look like?
Both are ugly hacks IMHO. Almost always there is a better solution. The real question to OP would be: why do you think you need it?
@RepWhoringPeeHaa look here: pastebin.com/bBS4iiMC I want to be able to pass a variable to the function that replaces "line29. $arrXml['Assignments']['Assignment']"
If eval() is the answer, you are asking the wrong question (or have an extreme lisp).
@halliewuud And you can't do $arrXml[ $var1 ][ $var2 ] because...?
|

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.