2

I have defined an array $array[1][1][test]="hello world". I would like to get this value by using variable variables. I have tried this, without success:

$var1="array";
$var2="[1][1]";
$var3="['test']";

echo ${$var1}{$var2}{$var3};

Output is null.

6
  • 3
    See The manual page for Variable Variables I dont think you can put the indicies into this concept though. Commented Jul 29, 2015 at 12:35
  • So you declaring a multi Dimensional array and you would like to display the values? Commented Jul 29, 2015 at 12:52
  • If you really really want to do this, you can use echo eval("return \$$var1$var2$var3;"). I would strongly advise against it, however. Commented Jul 29, 2015 at 12:55
  • I just knew someone would get to eval() eventually. Please read the CAUTION on the manual page before even thinking about using it. I bet if you stood back and looked at your requrement you could come up with something that worked without using eval() Commented Jul 29, 2015 at 13:07
  • 1
    @RiggsFolly, yes, eval() is kind of a like goto. It does great deal of damage when you don't know what you are doing and when you know enough to use it, you know you don't really need it. Commented Jul 29, 2015 at 13:12

2 Answers 2

0

I don't understand your question

If you get var try this:

echo $array[1][1][test];

"more dynamically":

$i = 1;
$x = 'test';

echo $array[$i][$i][$x];
Sign up to request clarification or add additional context in comments.

1 Comment

OP is asking for solution using variable-variables.
0

PHP manual doesn't cover use of variable-variable array indexes too thoroughly, but comments do mention that they don't work just as you have found out.

Some workarounds are provided, though:

$array[1][1]['test']="hello world"

$var1="array";
$var2="[1][1]";
$var3="['test']";

$tmp=$var1.$var2.$var3;

eval('echo $'.$tmp.';');

Above results in expected 'hello world' output. That said, I'd steer away from using eval() in any code.

Comment (by nick at customdesigns dot ca, dated 2006) on the manual page also provides function that can handle variable arrays with indexes, though.

2 Comments

Please read the CAUTION on the manual page before even thinking about using it.
Nice link to nicks comments. Much better idea than eval()

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.