Jump to content


Photo

How to increment a variable?


  • Please log in to reply
2 replies to this topic

#1 endy

endy
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 04 March 2006 - 10:41 PM

Hello,
I am trying to use a "while" loop to create a bunch of variables, however it doesnt seem to be working. Is there a way to concatenate a variable name with another variable? Here is what I am trying to do:
$i=0
while($i<5) {
$my_var.$i="something";
$i++;
}

So I just want to get a series of variables ($my_var1, $my_var2, $my_var3,...) that are all equal to "something";

Is it possable?
THanks!

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 04 March 2006 - 10:51 PM

Yes, you want to use variable_variables.
<?php
for ($i=0;$i<5;$i++) {
${'my_var'.$i}="something";
}?>
but it would be much easier to use an array here:
<?php
$myvar = array();
for($i=0;$i<5;$i++)
    $myvar[] = "somthing $i";
echo '<pre>'.print_r($myvar,true).'</pre>';
?>

Ken

#3 endy

endy
  • New Members
  • Pip
  • Newbie
  • 2 posts

Posted 05 March 2006 - 12:29 AM

cool thanks!




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users