I think it’s very convenient for us developers, being able to name our variables dynamically. I’ll show you how to do it in PHP. 🙂
For example, we have variable $foo
with “bar” as value like this:
1 2 |
<?php $foo = "bar"; |
If we want to create a variable named based on the “value” of variable $foo
, this is what we write:
1 2 3 4 |
<?php $foo = "bar"; $$foo = "My variable name is bar."; if(isset($bar)) echo $bar; |
The echo
should display: My variable name is bar.
Notice that the second variable that we declared was written as $$foo
with 2 dollar symbols before the variable name. This makes it a variable variable — a variable whose name is a variable. What happens is that it first gets the value of $foo, which is “bar” and then uses that value as the variable name. And so, in the example above, defining the variable as $$foo = "My variable name is bar."
is equal to defining it as $bar = "My variable name is bar."
.
Making the PHP variable name more dynamic
Now, what if you want to make your variable name more dynamic? I’ll give you another example.
Here we are generating a random 1-digit number, we’ll use it later:
1 2 |
<?php $numbers= array(1,2,3); |
The way that we’ll define the dynamic variables will be a bit different from the example earlier.
And here we have an array of strings:
1 2 3 4 5 6 7 |
<?php $words = array("uno", "dos", "tres"); for($x=0; $x<sizeof($words); $x++){ echo $words[$x]; } |
What if we want to create variables whose names are based on the value of strings in the array, like $uno
, $dos
, and $tres
?
We do it like in the code below. Notice that I defined my dynamically named variable like ${$v}
inside the foreach
:
1 2 3 4 5 6 7 8 9 10 11 |
<?php $words = array("uno", "dos", "tres"); for($x=0; $x<sizeof($words); $x++){ ${$words[$x]} = "variable $" . $words[$x] . " is defined! "; } if(isset($uno)) echo $uno; if(isset($dos)) echo $dos; if(isset($tres)) echo $tres; |
Now let’s use the $numbers
I showed you earlier. Pay attention to what I put inside the foreach
.
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php $numbers= array(1,2,3); $words = array("uno", "dos", "tres"); for($x=0; $x<sizeof($words); $x++){ ${$words[$x] . $numbers[$x]} = "variable $" . $words[$x] . $numbers[$x] . " is defined! "; } if(isset($uno1)) echo $uno1; if(isset($dos2)) echo $dos2; if(isset($tres3)) echo $tres3; |
The foreach let us define variables whose names are $uno1
, $dos2
and $tres3
, which are concatenated values from arrays $numbers and $words.
This is where the magic happens: ${$words[$x] . $numbers[$x]}
We combined elements from $words
and $numbers
arrays, then turned them into variable names by enclosing them in ${}
And that’s it! Use variable variables at your convenience. 🙂