The while loop has just one expression in it: the test to decide whether to continue. The initial values must be given before the loop and the increment must be inside the loop. If you do not make it possible for the loop to end, you have created an endless loop.
Example 1: The code below will print 1 2 4 8 16 32 64
$i=1;
while($i<100) {
echo $i.' ';
$i=$i*2;
}
The for loop is usually used when we know how many times we want the loop to execute. The while loop is used when it is not clear what the final value will be. A common error that creates an endless loop with the while is to give an exact end point in the example above, while($i!=100) would create an endless loop, as would leaving out the statement $i=$i*2; (or multiplying by 1)
Endless loops consume tremendous server resources. It is very important to check the loop by hand to see if the program is an endless loop before you upload it to the server.
Example 2: The code below will print January February March April May
$mth=1; //numeric representation of January
$date=mktime(0,0,0,$mth,1,2009); //January, any year
while($mth<6) {
echo date("F",$date).' '; //name of month
$mth++; //next month
$date=mktime(0,0,0,$mth,1,2009);
}
Experiment: