0

Its like this

I have a variable that has an array index in it, for e.g.

$var = 'testVar["abc"][0]';

or

$var = 'testVar["xyz"][0]["abc"]';

or it could be anything at run time.

Now when I try to access this by using this php code:

echo $$var;

or

echo ${$var};

I get a warning saying Illegal offset at line ...

but if I use this code, it works

eval('echo $'.$var);

I do not want to use eval(). Is there any other way?

EDIT:

The variable $testVar is an array build up on runtime and it could have multi-dimensional array built dynamically. Its format is not fixed and only the script knows by the use of certain variables that what the array could be.

for e.g. at any point, the array might have an index $["xyz"][0]["abc"] which I want to access dynamically.

My php version is 5.1

Imran Ahmed
  • 790
  • 1
  • 9
  • 22

1 Answers1

5

According to the documentation, what you are trying to accomplish is not possible:

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

In your case, $$var tries to read a variable with the name testVar["xyz"][0]["abc"], and not indexing an array. You could dereference that array like this:

$a = "testVar";
echo ${$a}["xyz"][0]["abc"];
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
  • Further solutions: http://stackoverflow.com/questions/10466815/php-variable-variables-with-array-key and http://stackoverflow.com/questions/2036547/variable-variables-pointing-to-arrays-or-nested-objects – Ofir Baruch Jan 13 '16 at 08:12
  • Actually I cannot use the approach you mentioned in the code above i.e. `$a = "testVar"; echo ${$a}["xyz"][0]["abc"];` because the actual part that is unknown at runtime is `["xyz"][0]["abc"]`, it could be anything at runtime – Imran Ahmed Jan 13 '16 at 08:18
  • @ImranAhmed I advise you to reconsider your software design. If you rely on variable variables like this, I think you should design it differently. If that is not possible (legacy code, time limits, etc) you are stuck with `eval`. – Bart Friederichs Jan 13 '16 at 08:21