Wild While Loops

Posted on 12. Mar, 2010 by admin in Basics


In the previous tutorial we covered loops. “While” loops are similar, but are best used in different situations. The concept is similar to what we learned earlier concerning if and switch statements, and how they can basically complete the same function, but each is better for certain tasks.

A while loop has a much simpler format than the for loop.Thinking back to the previous tutorial, the second argument in the for statement was a condition. In a while loop this is the only thing we need. Let’s use the example from the previous tutorial and repeat it in a while loop.


<?php
//First Declare the Counter Variable
$i=1;
//Same Conditional Statement as the For Loop
while($i <= 5)
{
echo "This is a test. ";
//Increment must be in the loop or
//we will have an infinite loop
$i++;
}
?>

The comments above should provide some guidance regarding how the while loops are similar to for loops. We cannot declare the counter variable inside the statement, we must declare it before. Also, we must make sure to make the counter variable change inside the loop or it will just go on forever.

It’s best to use while loops when you want the loop to be dynamic rather than static. For our for loop example we counted down from 10 to 0. We knew that we needed to count down from 10 to 0, so it was quite easy to use a for statement to do this. You would use a while if you really did not know.

For example, if you wanted to count from two random numbers, in this case 6 to 17, your code would look something like this:


<?php
$start = 6;
$end = 17;

echo "We are counting from ".$start." to ".$end.". ";

while($start <= $end)
{
echo $start."... ";
$start++;
}

echo " All Done!";
?>

Output:

We are counting from 6 to 17. 6… 7… 8… 9… 10… 11… 12… 13… 14… 15… 16… 17… All Done!

It is up to you to decide if you want to used Wild While Loops or Flash For Loops.