While

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:

  1. Rewrite this to use a for loop.
  2. Print all of the months of the year.
  3. Print all of the months after the current month.
  4. Write a loop that will print out the days of the week.
  5. Create a table that tells the name of the month in one column and the number of days in the second column: date("t",$date);

INDEX, Loops: Introduction, Loops: while, Loops: do while, Nested Loops
Next lesson: ArraysMAIN INDEX
EXAMPLES INDEX

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Loops: while