Loops

The WHILE Loop

The WHILE loop is one of the most useful and simple commands in PHP.

It is composed of a body containing some instructions and an exit condition. At the beginning of the cycle and each successive iteration, all the instructions in the body are executed, the exit condition consisting of a boolean expression, is checked up. The loop ends when the exit condition returns a false value.

So it executes a piece of code until a certain condition is met.

If you have a piece of code which you want to repeat several times without retyping it, you can use a while loop.

Basic form :

while (expr)

statement

or, if need to execute multiple statements you could use :

while (expr):

statement

...

endwhile;

Sample code:

$no = 10;

$x = 0;

while ($x < $no) {

echo "Test script";

++$x;

}

The variable $no holds the number of times you need to execute the code and $x (variable x) will count how many times code has been executed.

After a line is printed variable x is incremented by 1 and the test $x>$no is performed again.

do-while

do-while loops are very similar to while loops, except the truth expression is checked at the end of each iteration instead of in the beginning. Therefore the statement will be run at least once if you will use do-while instead of while.

Basic form :

do

{
statement...

} while (condition)

for loops

Basic form :

for (expr1; expr2; expr3)

statement

The first expression (expr1) is executed once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Comparisons
of for and while loops
for
Loop
while
loop
for
($i=0; $i<=10; $i++) {

echo("Iteration
no. $i<BR>");

}
$i=0;

while ($i<=10) {

echo
("Iteration no. $i<BR>");

$i++;

}

admin – Thu, 2005 – 07 – 07 11:58