How to Create and Use Dynamically Named Variables with PHP

Posted in php by ShortLikeAFox on August 17th, 2008

So you want to use dynamic variable names in your code. No problem. Let’s say you have 100 variables named dog0, dog1, dog2, …., dog98, dog99. Why you would want to use 100 variables like this instead of an array is beyond me, but it doesn’t matter for this example. To set these variables in a quick loop you could use the following:

for ($i = 0; $i < 100; $i ++){

$variableName = "dog$i";
$$variableName = $i; //sets $dog1 to 1, $dog2 to 2, $dog 34 to 34, etc….

}

Now let’s say you wanted to access all of these variables. You could use the following:

for ($i = 0; $i < 100; $i ++){

$variableName = "dog$i";
echo("<br/>");
echo("$variableName: ");
echo($$variableName);

}

This loop prints:

dog0: 0
dog1: 1
dog2: 2
dog3: 3
dog4: 4
dog5: 5
dog6: 6
dog7: 7
dog8: 8

etc… all the way to
dog99: 99