How to Create Dynamic PHP Variables

When I speak of “dynamic” variables or “variable” variables, what I mean is to create a variable name using PHP so that variable names are created dynamically. It sounds confusing and it sometimes hurts to think about things like this, so let’s just break it down and make it simple because it’s really not too complex at all. The best way to explain is with a PHP code example. Consider the following PHP code:

<?php

$v = ‘new_var’;

$$v = ‘variable contents of new_var…’;echo $new_var;

?>

The above PHP code will output:

variable contents of new_var…

Pretty neat huh? You might be asking yourself how this could come in handy or, more likely, you came here because you aready have a use in mind. I’ll continue to explain some common usage cases below.

Why Use Variable Variables or Dynamic Variables:

Imagine that you have 6 people’s ages stored in php variables like this:

<?php

$age1 = 20;
$age2 = 50;
$age3 = 21;
$age4 = 63;
$age5 = 18;
$age6 = 19;

?>

Okay, now lets pretend you want to call these variables from age1 to age6 in a loop. Using the concept of variable variables, you could do this:

<?php

$age1 = 20;
$age2 = 50;
$age3 = 21;
$age4 = 63;
$age5 = 18;
$age6 = 19;

for($i=1; $i < 7; $i++){

$v = “age$i”;

$cur_age = $$v;

echo “$i – $cur_age yrs old<br />”;

}

?>

The above snippet will print:

1 – 20 yrs old
2 – 50 yrs old
3 – 21 yrs old
4 – 63 yrs old
5 – 18 yrs old
6 – 19 yrs old

Good so far. You can also use curly brackets so considering the code above, you could replace:

$cur_age = $$v;

with:

$cur_age = ${$v};

which may in some cases make things easier.

Summary

There are all sorts of uses for Dynamic or Variable PHP Variables. After you have written enough code, you will surely come across all sorts of problems where the solution is a dynamically created variable name. Sometimes for more complex generated names, curly brackets come in handy. Good luck with your next project using variable variables and happy coding!

Leave a Reply

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