John Goche
John Goche

Reputation: 433

PHP: using variable value as variable name: curious about syntax issue

Suppose I have the following:

$foo = "bar";
$bar = "hello";

Then the string "hello" can be echoed to standard output as either:

echo $$foo;

or

echo ${$foo};

I was wondering what the difference is between these two statements in general. That is, what is the purpose of the braces around the evaluated variable name in the second syntax displayed above?

Upvotes: 3

Views: 1936

Answers (2)

Blaster
Blaster

Reputation: 9080

There is no difference between the two in what they do in YOUR example.

The first example is concept knows as Variable Variables while the second braces example allows you to generate dynamic variables based on specified values.

You may also want to checkout:

Upvotes: 3

Mathieu Dumoulin
Mathieu Dumoulin

Reputation: 12244

The only reason to use ${$foo} is to be able to combine $foo to something else, for example:

$idx = 4;
$bar3 = 20;
$bar4 = 7;
echo ${$foo.$idx}

This would return the value in $bar4 since $idx is worth 4;

Upvotes: 8

Related Questions