Main Content

Double Dollars in PHP

Archive - Originally posted on "The Horse's Mouth" - 2005-11-02 23:17:57 - Graham Ellis

What does this print?

<?php
$first = "fur";
$last = "feather";
$$first = "yum yum ";
${"$first$last"} = "yikes";
print "$fur $furfeather";
?>

It prints "yum yum yikes".

In PHP, you can write a variable name within a variable name, and that's what I've done in this example.

The variable called "first" is set to contain the word "fur"
The variable who's name is in first - so that's the variable called fur - is set to "yum yum"

The variable called "last" is set to "feather"
The variable who's name is made up of the string in the variable first followed by the string in the varaible last - so that's the variable called furfeather - is set to "yikes".

This is a facility to be used sparingly - it's quite easy to write code that's unmaintainable using such structures, though they can be very useful at times for helping to generalise code.