Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 340
John Goche Avatar asked Sep 10 '26 07:09

John Goche


1 Answers

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;

like image 142
Mathieu Dumoulin Avatar answered Sep 12 '26 22:09

Mathieu Dumoulin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!