2
$var = "array";
$$var=array("1","2");

How can I call the array in $$var without using foreach? I want a method like $$var[0], but this doesn't work.

1
  • 3
    using variable variables is rarely a good idea.. use a better data structure. Commented May 17, 2012 at 11:17

3 Answers 3

3

Use it like this:

echo ${$var}[0];
Sign up to request clarification or add additional context in comments.

Comments

2

When you run this piece of code:

$var = "array";
$$var = array("1","2");

...it is identical to this:

$array = array("1","2");

So you can do this:

echo $array[0];

...or this:

echo ${$var}[0];

If you must use variable variables - and 99.99% of the time arrays are a better solution - you should always use braces for clarity and disambiguation.

See the variable variables reference for more information.

Comments

0

You need some curly braces:

${$var[1]} 

OR

${$var}[1]

depending on which variable you are accessing.

Comments

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.