0

I want to use a forloop to create a number of vars... their names are $var1 to $var15. How do I do that? I'm doing $$var.$i but it's not working.

for($i=1; $i <= 15; $i++){
   $$var.$i = 'this is the content of var'.$i;
}
sameold
  • 18,400
  • 21
  • 63
  • 87
  • very similar question: [Print a variable through a 'for' in PHP](http://stackoverflow.com/q/7296381) – Jeremy Sep 14 '11 at 05:33

1 Answers1

4

If you wanted to do that, exactly, you would have to do ${$var . $i} instead. Right now it's being interpreted as ($$var).$i.

However, this is very bad style. Instead, you should use an array[php docs] to store the values:

$var = array();
for($i=1; $i <= 15; $i++){
    $var[$i] = 'This is the content of $var['.$i.'].';
}

var_export($var);
Output:
array (
  1 => 'This is the content of $var[1].',
  2 => 'This is the content of $var[2].',
  3 => 'This is the content of $var[3].',
  4 => 'This is the content of $var[4].',
  5 => 'This is the content of $var[5].',
  6 => 'This is the content of $var[6].',
  7 => 'This is the content of $var[7].',
  8 => 'This is the content of $var[8].',
  9 => 'This is the content of $var[9].',
  10 => 'This is the content of $var[10].',
  11 => 'This is the content of $var[11].',
  12 => 'This is the content of $var[12].',
  13 => 'This is the content of $var[13].',
  14 => 'This is the content of $var[14].',
  15 => 'This is the content of $var[15].',
)

This is more efficient and often safer.

Jeremy
  • 1
  • 85
  • 340
  • 366