PHP Dynamic Variables

This is otherwise known as “Variable variables”. Let’s begin.

Basically in PHP, we assign value to a variable like this:

$var = "word";

If we want a variable whose name is the value of the $var variable, we do so like this:

$$var = "press"; // $word = "press"

PHP parses $$var by first de-referencing the innermost variable, which means that $var becomes “word”. The expression that’s left is $word. This defines a new variable named word and assigned it the value “press”. We can nest dynamic variables to an infinitely in PHP, although this is not recommended because it can be very confusing once it gets beyond 2 to 3 levels.

There is a special syntax for using Variable variables, and any other complex variable, by calling the variable inside curly brackets:

echo "${$var}";

This syntax also helps resolve an ambiguity that occurs when defining Variable arrays. In order to use Variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Variable variables may not seem that useful and even confusing, but there are times when they can reduce the amount of code needed. For example, in an associative array that looks like:

$array[“hello”] = “word”;
$array[“world”] = “press”;

Associative arrays like this are returned by various functions in the PHP modules. mysql_fetch_array() is one example. The indices in the array usually refer to fields or entity names within the context of the module you are working with. It’s handy to turn these entity names into real PHP variables, so you can refer to them as simply $hello and $world. This is done as follows:

foreach( $array as $index=>$value ) {
    $$index = $value;

Leave a Comment