Using Variable Variables

PHP allows you to use dynamic variable names, called variable variables. You
can name a variable by using the value stored in another variable. That is, one
variable contains the name of another variable. For example, suppose you want
to construct a variable named $city with the value Los Angeles. You can use
the following statement:

$name_of_the_variable = “city”;

This statement creates a variable that contains the name that you want to
give to a variable. Then you use the following statements:

$$name_of_the_variable = “Los Angeles”;

Note the extra dollar sign ($) character at the beginning of the variable name.
This indicates a variable variable. This statement creates a new variable with
the name that is the value in $name_of_the_variable, resulting inthe
following:

$city = “Los Angeles”;

The value of $name_of_the_variable does not change.

The following example shows how this feature works. In its present form, the
script statements may not seem that useful; you may see better ways to program
this task. The true value of variable variables becomes clear when they
are used with arrays and loops, as discussed in Chapters 6 and 7.

Suppose you want to name a series of variables with the names of cities that
have values that are the populations of the cities. You can use this code:

$Reno= 360000;
$Pasadena = 138000;
$cityname = “Reno”;
echo “The size of $cityname is ${$cityname}”;
$cityname = “Pasadena”;
echo “The size of $cityname is ${$cityname}”;

The output from this code is:

The size of Reno is 360000
The size of Pasadena is 138000

Notice that you need to use curly braces around the variable name in the
echo statement so that PHP knows where the variable name is. If you use the
statement without the curly braces, the output is as follows:

The size of Reno is $Reno

Without the curly braces in $$cityname, PHP converts $cityname to its
value and puts the extra $ in front of it, as part of the preceding string.

Leave a Comment