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.

Julian
  • 127
  • 1
  • 5
  • 3
    See [The manual page for Variable Variables](http://php.net/manual/en/language.variables.variable.php) I dont think you can put the indicies into this concept though. – RiggsFolly Jul 29 '15 at 12:35
  • So you declaring a multi Dimensional array and you would like to display the values? – Reagan Gallant Jul 29 '15 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. – Phylogenesis Jul 29 '15 at 12:55
  • I just knew someone would get to `eval()` eventually. Please read the [**CAUTION** on the manual page](http://php.net/manual/en/function.eval.php) 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()` – RiggsFolly Jul 29 '15 at 13:07
  • @RiggsFolly Yeah. That's why I tried to put a big warning around its use and left it as a comment rather than an answer. – Phylogenesis Jul 29 '15 at 13:08
  • 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. – vhu Jul 29 '15 at 13:12

2 Answers2

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];
Javi
  • 506
  • 3
  • 15
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.

vhu
  • 12,244
  • 11
  • 38
  • 48