Learning Loops in Php: The While and Do-While Loops

Learning Loops in Php: The while and do-while Loops
by admin admin Date: 11-04-2013

While loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:


while (expr)

This is why a for loop is suitable when you have to carry out a finite number of actions.
There may be times though when you need to carry out repetitive actions for an unspecified number of iterations. In this circumstance either of the while or do-while loops is ideal.

The meaning of a while statement is simple: It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE.
The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the whileexpression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once. Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax: 

<?php/* example 1 */
$i = 1;
while ($i <= 10) {
echo $i++;  /* the printed value would be
$i before the increment
(post-increment) */}
/* example 2 */
$i = 1;
while ($i <= 10):
echo $i;

This other example illustrates a do-while loop that reads a file and prints the contents. The loops are similar except the truth expression that is checked at the end of each iteration instead of in the beginning.

$i = 0;
do {
echo $i;
} while ($i > 0);?>

See also For Loop and For each Loop

by admin admin Date: 11-04-2013 hits : 1242