I remember once watching a documentary on Arnold Schwarzenegger’s bodybuilding career (or was it this one?) in the ’70s and early ’80s.

All of the bodybuilders in that golden era had their own training programme managers and promoters.  I recall that one manager/promoter, working for another bodybuilder, loved his own quotes.

These quotes would range from the urbane, “the pen is mightier than the muscle”, to somewhat more characteristically humorous: “remember the golden rule: he who has the gold, makes the rules“.

Well, in the completely unrelated world of PHP programming, this perl of wisdom (sic joke) is worth hanging on to.  Why?  Well, if you have ever used PHP’s variable variables, knowledge of the correct syntax is worth its weight in gold.  It’ll save hours, if not days, of debugging.
So, anyway, I’ve been coding a calendar system for a valued client for the past ten days or so.  My first attempt I pretty much scrapped as it got too complex and almost impossible to debug.  The second version is much better, except for one issue which has been giving me grief until now.

Variable variables in PHP are extremely useful, but I throw in a word of caution immediately: use them sparingly.  It can be easy to quickly lose track of what’s called what and why it’s there.  Especially if any single script is 400+ lines long.

To set a variable variable, it’s easier to start off giving a value to an ordinary variable:

$myVar = "myVarVar";

Now, I want to create a variable variable with the name $myVarVar, so this is how it’s done:

$$myVar = "this is my variable variable";

To see the contents of the variable variable, you can do either of the following:

echo $$myVar;     // or
echo $myVarVar; 

Both will output “this is my variable variable” to the screen/page.

Snooker Loopy
Things start getting interesting when you introduce arrays and loops. Take the following example:

for($i=0; $i<4; $i++) {
$myVar = "myVarVar".$i;
$$myVar = "  Variable variable £".$i;

creates and produces:

echo $myVarVar0; // "Variable variable #0"
echo $myVarVar1; // "Variable variable #1"
echo $myVarVar2; // "Variable variable #2"
echo $myVarVar3; // "Variable variable #3"

Have your say!