Member-only story
PHP — P13: Variable Variables

Variable variables: no that’s not a typo. That’s what this topic is about. A variable variable is a dynamic variable, meaning that you can generate variable names dynamically in PHP. How is this done? If you prepend a dollar sign to a string, the string will then become a variable.
View this article and others on my website.
Let’s create a regular variable $a. The variable $a will contain the string “bear.” We’ll then create another variable, and this time we’ll add an additional dollar sign before it. We’ll call the new variable variable $$a.
<?php
$a = "bear";
$$a = "cow";echo $a;
echo $$a;
?>
If we echo out both variables, PHP will see the first regular variable, $a, and will retrieve the data it’s storing. It contains the string “bear.” It evaluates the string and outputs it to the screen. It moves to the next statement and sees the variable variable $$a. It starts with the initial variable $a and retrieves the string “bear.” It then prepends another dollar sign to it, making a variable $bear. Technically $$a is $bear. So it retrieves the content that $bear is pointing to, which is “cow,” and outputs it to the screen.
I wanted to start off with an example that’s a little more challenging, just to get it out of the way and just to get the wheels turning. Let’s move on to a more practical example. Let’s create two variables again, $mouse and $animal. The variable $mouse will contain the string “Small” and the variable $animal will contain the string “mouse.”
<?php
$mouse = "Small";
$animal = "mouse";echo $animal;
echo $$animal;
?>
If we echo out $animal, PHP will see that it stores the string “mouse” and will output it to the screen. The statement that’s echoing out $$animal will be interpreted a little differently than the first statement. PHP will take the following steps:
- It retrieves the string “mouse” that $animal is pointing to.
- It prepends a dollar…