Loops

PHP has several types of loops: for, while, do..while, and foreach. In this lesson we will discuss the first three. We will discuss foreach in the lesson on arrays.

The for and while loops do a test at the beginning and thus execute zero or more times. The do while loop does the test at the end and thus always executes at least once.

for Loop

The for loop usually has one variable that drives the loop. the first expression in a for loop usually gives this variable a value and is executed once when the loop begins. The second expression is evaluated to true or false, if true the loop goes through, then executes the third expression and then performs the test again. When the test fails (is false) the program continues with the next statement after the loop.

Example 1: The code below will print 1 2 3 4 5 6 7 8 9 10

for($i=1;$i<=10;$i++) echo $i.' ';

Example 2: The code below will print the table that converts inches to centimeters (1"=2.54 centimeters)

echo '<table width="200" border="1"><tr><th scope="col">Inches</th><th scope="col">Centimeters</th></tr>';
for($i=1;$i<=6;$i++) {
  echo '<tr><td>'.$i.'</td><td>'.$i*2.54.'</td></tr>';
}
echo '</table';
InchesCentimeters
12.54
25.08
37.62
410.16
512.7
615.24

Experiment: Review the number_format function and make the values in the table align correctly. Create a different table doing some other metric conversion.


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

Copyright © Zebra0.com
All rights reserved worldwide.

 
 

Loops: Introduction