PHP while loop problems
I am primarily a CSS and HTML guy but I have recently ventured into PHP.
I can't see why this scr开发者_Go百科ipt hangs:
$loop_Until = 10;
while($i < $loop_Until)
{
// do some code here
$loop_Until = $loop_Until + 1;
}
Can anyone please help?
Fixed Code
$loop_Until = 10;
$i = 0;
while($i < $loop_Until)
{
// do some code here
$i = $i + 1;
}
Explanation of your code:
// A variable called loop until is set to 10
$loop_Until = 10;
// While the variable i is less than 10
// NOTE: i is not set in code snippet, so we have no way of knowing what value it is, if it is greater than 10 it might be infinite
while($i < $loop_Until)
{
// Increment the 10 value up 1 every time, i never changes!
$loop_Until = $loop_Until + 1;
}
This is causing an ifinate loop, youo will want to take a look at the php for
loop. http://php.net/manual/en/control-structures.for.php
for($i= 1; $i< $loop_Until; ++$i) {
// do some code here
}
You are increasing $loop_Until
every time and never increaing $i
therefore $i
will always be less than $loop_Until
Simplest solution: Replace your "+" with a "-". This will cause the loop to end. Like this:
$loop_Until = 10;
while($i < $loop_Until)
{
// do some code here
$loop_Until = $loop_Until - 1;
}
Let me explain, provide a slightly better solution, and give you a few alternatives.
If we assume that $i starts out as smaller than $loop_Until, then adding 1 to $loop_Until with the line $loop_Until = $loop_Until + 1;
would never make it so that $i is equal or greater than $loop_Until.
You should either subtract from $loop_Until, or add to $i.
Subtracting 1 from a variable can be done quickly by doing, --$variable
.
Adding 1 to a variable can be done quickly by doing, ++$variable
, so you should have:
$loop_Until = 10;
while($i < $loop_Until)
{
// do some code here
--$loop_Until;
}
Of course $loop_Until sounds like something you might want to set once, and then have it stay unchanged. In this case, you can set $i and increment that. So first set $i to whatever you want (smaller than $loop_Until, if you want your while loop to run at least once), then:
$loop_Until = 10;
while($i < $loop_Until)
{
// do some code here
++$i;
}
Incidentally, ++$i is faster than $i++
As Lizard mentioned, the for loop is great for doing this. The two equivalent for loops for the two sections of code above are
for($loop_Until = 10; $i < $loop_Until; --$loop_Until)
{
// do some code here
}
and
for($loop_Until = 10; $i < $loop_Until; ++i)
{
// do some code here
}
Just make sure you check that your condition will eventually happen with a few numbers on a piece of paper or in your head.
Finally, which of these solutions you pick will depend on whether you want $i or $loop_Until to remain unchanged.
If you have multiple loops, and you want to do all of them the same amount of times, it's probably a good idea to leve $loop_Until untouched, and reset $i at the beginning of each loop.
while( 0 != ($loop_until--) );
精彩评论