• You are not logged in. | Login

Post a reply

November 16, 2006 3:33 am

yendii
Member
Ranks

how do i increment a variable?

Hello,

I want to make a loop to create a bunch of variables, like this

i=0;
while($i<5){
$myvar . $i= "something";
$i=$i+1;
}

and I want to get "$myvar1, $myvar2, $myvar3" and so on but it's not working

I tried a bunch of stuff but i dont know what i'm doing wrong


 

 

November 16, 2006 3:49 am

IBdaMac
Member
Ranks

Re: how do i increment a variable?

You've got the .$i in the wrong place

change it to:

$myvar = $i . "something";


 

 

November 16, 2006 3:54 am

phppat
Member
Ranks

Re: how do i increment a variable?

Your best bet in this situation is to use an array, really.

while ( $i < 5 ) {
$myvar[] = "something;
}

This will give you $myvar[1], $myvar[2], and so on, with the convenience of storing all of the values in one variable name ($myvar).

If you need to have seperate variables, try this instead:

$( 'myvar' . $i ) = "something";

This will give you the intended '$myvar1, $myvar2' and so on.


PHP monster

 

 

November 16, 2006 3:55 am

yendii
Member
Ranks

Re: how do i increment a variable?

Thanks!

the first one didn't work, i just ended up with $myvar = "5something"

i'll try the arrays, thanks!


 

 

November 16, 2006 6:37 pm

yendii
Member
Ranks

Re: how do i increment a variable?

Ok so i think i got the arrays thing, but im not getting all 5 variables, i just get $my_var[1], $my_var[2], $my_var[3] and $my_var[4], but $myvar[5] is blank!

what am i doing wrong?


 

 

November 16, 2006 6:43 pm

phppat
Member
Ranks

Re: how do i increment a variable?

Sorry yendii, that was my bad for being unclear.

When you create an array with that while loop, the indicies ( the [x] part of $my_var[x] ) always start at ZERO and not at 1, so your values start at $my_var[0] and go to $my_var[4], for a total of 5 elements (variables in the array)

Hope that clears it up for you!


PHP monster

 

 
  • Actions
  • Top
ITCrimea. Ukraine Web Development Company. Professional Developers and Web Designers Team
Custom Web Designs, Internet Applications, E-Commerce Websites, Interactive Sites, Database-Driven Sites and Services