I just recently read and later groked the concept of Variable Variables. The PHP manual, from which I was reading, didn't seem to sufficiently explain them, and didnt provide any examples. They are rather hard to explain, so here is an example:

<?php
$Foo='Var1';
$Var1='Hello World';
print $${$Foo};
?>
This will print "Hello World", here is how it works. Sometimes, for whatever reason, you want PHP to be very sure of the variable you are dealing with. So you will interact with the variable as ${Bar} instead of simply $Bar. Their both the same thing, but since you have enclosed 'Bar' inside '{}' there can be no mixup with variables next to each other in strings or whatnot. Now with variable variables, you can use a variable as a name of a variable. Say you have a variable $Bar that contains the string 'XYZ', and a variable $XYZ that contained 'boo!' Calling ${Bar} would give you 'XYZ'. Calling ${$Bar} would give you nothing, because that is incorrect syntax. But calling $${$Bar} would give you 'boo!'.

It works in reverse to, with the creation of variables. Say $a=var. $$a=test would create the variable $var and set it to 'test'.

The following example is written to handle a dynamically generated form with lots of sequentially numbered inputs. An array containing all the field names was created when the form was run, and passed on through the use of PHP Sessions.

<?php
foreach($_SESSION['FormInputs'] as $InputNumber){
echo $InputNumber; //This would display the variables themselves as strings, ie. "Cell-1 Cell-2 Cell-3"

echo $${$InputNumber}; //This would display the values in the variables $Cell-1 $Cell-2 $Cell-3
}
?>

There is only one limitation on Variable Variables in PHP, which is that they cannot be used with the superglobals such as $_GET and $_POST.

Log in or register to write something here or to contact authors.