PHP Variable Variables
By Dillon Smart · · · 0 Comments
In PHP, it is sometimes necessary to have variables that have variable names. Traditionally, a variable is given a name and a value is given to the variable like so:
$foo = 'bar';
A Variable Variable, or Double Dollar Variable, gets its name from the value of another variable like so:
$foo = 'bar'; $$foo = 'Foo Bar'; echo $bar; // output 'Foo Bar'
In the example above, the Variable Variable has been given the name of foo. The use of the double dollar operator gives the variable the name which is the value of foo. In this case, the value of foo is bar.
Limitations of using Variable Variables in PHP
Although PHP has the Variable Variable operator built-in, there are reasons to use more traditional ways of assigning values. The biggest drawback of Variable Variables is speed.
PHP Variable with an assigned value
PHP Array with one key-value pair
PHP Variable Variables
As you can see, there is a significant speed difference when using Variable Variables. Wherever you have data that you could access using a Variable Variable, an array should be used for the most efficient code.
Learn more about Variable Variables in the official documentation.
0 Comment