PDA

View Full Version : How to increment a variable?



endy
March 4th, 2006, 05:35 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!

Templarian
March 4th, 2006, 05:41 PM
that wont work how your setting up your variables currently.

$i=0
while($i<5) {
$my_var[$i]="something";
$i++;
}
Use an array for this sort of thing.

λ
March 4th, 2006, 07:12 PM
Yeah, you'd use an array for this kind of thing :)

Although this should work:



<?php
$i = 1;
while ($i <= 5) {
$name = "my_var" . $i;
$$name = $i;
$i++;
}
?>


That will create 5 variables with names from $my_var1 to $my_var5.

endy
March 4th, 2006, 07:27 PM
thanks guys, worked great!