Return to Snippet

Revision: 58829
at August 4, 2012 00:06 by dialeleven


Initial Code
// create fifty (50) variable named variables named my_var1, my_var2...
$name = "my_var";

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

${$name.$i} = rand();

}

echo $my_var3;


// slightly more complex example to create a variably named array w/concatenation
$name = "my_var";

for ($i = 1; $i <=5; ++$i)
   ${$name . $i . '_arr'} = rand();

echo $my_var2_arr;

Initial URL
http://www.justskins.com/forums/variable-in-variable-name-96140.html

Initial Description
Create variable named PHP variables. Having dynamically named variables can be helpful when dealing with loops and arrays. For example instead of having seven if () statements for handling seven individual days of the week, you could reduce it to one if statement by doing a loop with seven iterations and dynamically create your variable names.

Initial Title
Variable in PHP variable names

Initial Tags
php

Initial Language
PHP