Hudzilla.org - the homepage of Paul Hudson
Contents > Simple variables and operators Wish List | Report Bug | About Me ]

3.7     Variable variables

This is NOT the latest copy of this book; click here for the latest version.

Variable variables are somewhat complicated to use, and even more complicated to explain, so you might need to reread this section a few times before it makes sense. Variable variables allow you to access the contents of a variable without knowing its name directly - it is like indirectly referring to a variable. Consider this piece of code:

<?php
    $bar
= 10;
    
$foo = "bar"
?>

There are two ways we can output the value of $bar here. We can either use print $bar, which is quite straightforward, or we can take advantage of the concept of variable variables, and use print $$foo;. That's right - two dollar signs.

By using $$foo, PHP will look up the contents of $foo, convert it to a string, then look up the variable of the same name, and return its value. In the example above, $foo contains the string "bar", so PHP will look up the variable named $bar and output its value - in this case, 10.

Variable variables are fairly clumsy to use, but they can be helpful when you are stuck. Furthermore, they only really get more clumsy the more indirection you use. For example, this next script outputs "Variable!" four times, but I hope you agree it is not very easy to read!

<?php
    $foo
= "Variable!\n";
    
$bar = "foo";
    
$wom = "bar";
    
$bat = "wom";
    print
$foo;
    print $
$bar;
    print $$
$wom;
    print $$$
$bat;
?>




<< 3.6 Variable scope   3.8 Superglobals >>
Table of Contents
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.



My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!



Top-right shadow
 
Bottom-left shadow Bottom shadow

Comments from other readers
jlx - 07 Jan 2009

the same result with pointers in C

#include <stdio.h>
int main(int argc,char **argv)
{
char *foo = "Variable!\n";
char **bar = &foo;
char ***wom = &bar;
char ****bat = &wom;

printf("%s\n", foo);
printf("%s\n", *bar);
printf("%s\n", **wom);
printf("%s\n",***bat);

return 0;
}

A PHP User - 07 Jan 2009

Is there any way to set variable variables? (You only explain how to call variable variables.)

An example:
I want to make a tool for an massive multiplayer online game and first I want to add some data of the players to a database. I made a form that asks how many villages the player has. When submitted a form is created to ask for the villagename, x- and y-coordinates of every village. So far no problem. When submitted a third form is created to fill in the coodinates and the name of each village.
So if a player has only one village I want to get village1 (the name), x1 and y1 (the coordinates) of the previous form. If a player has two villages I also want to get village2, x2 and y2, and so on. Is there any way to do this?
Here is the code I tried:

$villages = $_POST['villages'];
$i = 0;
while ($i < $villages) {
$i += 1;
$variable1 = "village".$i;
$variable2 = "x".$i;
$variable3 = "y".$i;
$$variable1 = $_POST['$variable1'];
$$variable2 = $_POST['$variable2'];
$$variable3 = $_POST['$variable3'];
}
and then printing things like:
$i = 0;
while ($i < $dorpen) {
$i += 1;
$variabele1 = "village".$i;
$variabele2 = "x".$i;
$variabele3 = "y".$i;
print "$$variabele1\r\n";
print "$$variabele2\r\n";
print "$$variabele3\r\n";
}
But this returns the variable names instead of the values. (E.g. '$x1' instead of '23'.) Is there any way to solve this?

A PHP User - 07 Jan 2009

amazingly i got it the 1st time i read this
i must mean you know how to explain things...
THANKS :)
hopefully i wont be a php noob once im done with this book :)
ill be... beginner :P

Invalidsyntax - 07 Jan 2009

WHAT RHE Heck is this lol im lost here lol

php newbie - 07 Jan 2009

Form Input == <?php
foreach($province as $val)
{
echo'Improve Province '."$val"."<INPUT TYPE=\"CHECKBOX\"
NAME=\"provImprove$provCount\"
value=\"player $username improves province $val\">". "<BR/>";
$provCount++;
?>

Form Output == <?php

for($i=0;$i<$provCount;$i++)
{
$temp = '$provImprove';
$temp .="$i";
echo"$$temp";
echo"<BR/>";
}
?>
The problem: The variable variable,while character for charcter is the same as desired variable name "$proveImprove0", doesn't echo the desired string, but echo"$proveImprove0"; does.

A PHP User - 07 Jan 2009

is this a necessary feature - probably not.
is it useful - occasionally
this feature makes it very difficult to compile PHP further than to byte code which is why languages like C don't have a similar feature.

Giri - 07 Jan 2009

is there any application...do we use it often?

Joe - 07 Jan 2009

Would this ever really be necessary?

Sker - 07 Jan 2009

The last statement of a php island doesn't need a semicolon

jimbo - 07 Jan 2009

$foo = "bar"

add the ;



Add comment
Please note that by posting a comment here you are committing it to the public domain. This is important so that others can make use of your code themselves, and also so that I can incorporate helpful notes directly into the main text. Comments are limited to 2000 characters in length.

If you are reporting an error in the content, please tell me directly.

Your name/email address:
Your comment:
 
Now, in order to verify that you're a real person, please answer this simple question: what is two plus five?
The answer is:
(please write in
numbers, eg 19)


Top-right shadow
 
Bottom-left shadow Bottom shadow