PHP dynamic variable names tutorial

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:

If we want to create a variable named based on the “value” of variable $foo, this is what we write:

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:

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:

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:

Now let’s use the $numbers I showed you earlier. Pay attention to what I put inside the foreach.

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. 🙂

Catzie

A Filipino who is a mobile & web developer on weekdays, and a baker on weekends. When I have time to spare, I blog, play video games, watch series (usually anime), cook dishes, draw, or spend a little time with pets. When I have the rare luxury of time, I get to travel and record song covers too! Follow on Twitter: @catzie

Leave a Reply

Your email address will not be published. Required fields are marked *