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

Learning Loops in Php: The while and do-while Loops
by Janeth Kent 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)
statement

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;
$i++;
endwhile;?>

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.
 

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

See also For Loop and For each Loop

 
by Janeth Kent Date: 11-04-2013 hits : 1386  
 
Janeth Kent

Janeth Kent

Licenciada en Bellas Artes y programadora por pasión. Cuando tengo un rato retoco fotos, edito vídeos y diseño cosas. El resto del tiempo escribo en MA-NO WEB DESIGN END DEVELOPMENT.

 
 
 

We use our own and third-party cookies to improve our services, compile statistical information and analyze your browsing habits. This allows us to personalize the content we offer and to show you advertising related to your preferences. By clicking on "Understood" YOU AGREE TO THE USE OF THESE COOKIES. You can also SET OR DISCONTINUE the installation of cookies by clicking on "Settings" or "Reject".


Understood Reject Settings More Info