Web Development Tutorials




  
  

While-Loop Structure

In programming it is often necessary to repeat the same block of code a number of times. This can be accomplished using looping statements. PHP includes several types of looping statements. This section focuses on the while loop.

The while statement loops through a block of code as long as a specified condition is evaluated as true. In other words, the while statement will execute a block of code if and as long as a condition is true.

The basic while loop syntax is shown below:

while (condition) {
    //code to be executed;
} 

The code within a while loop will repeatedly execute as long as the condition at the beginning of the loop evaluates to true. The code block associated with the while statement is always enclosed within the { opening and} closing brace symbols.

The following example demonstrates a while loop that continues to execute as long as the variable $number is greater than or equal to 2:

<?php 
     $number = 5;
     while ($number >= 2) {
        echo $number . "<br/>";
        $number -= 1;
     }
?>

In the above example, the variable $number is initialized to 5. The while loop executes as long as the condition, ($number >=2), or $number is greater than or equal to 2, printing the value of $number to the browser window. At the end of the loop block, the value of $number is decreased by 1.

Below is the output generated by the sample loop:

  5 
  4 
  3 
  2 

During the first run, the value of $number is equal to 5. Since 5 is greater than 2, the echo statement is used to display the value 5. A <br> is concatenated to the display to create a carriage return each time the loop is processed. Next, the value of $number is decreased by 1. During the second iteration, the value of $number is equal to 4. Since 4 is greater than 2, the echo statement displays the value 4. This process continues while the value of $number is 3 and 2. When $number is equal to 2, the echo statement displays the value 2 and the value of $number is then decremented to 1. Since 1 is not greater than or equal to 2, the condition is no longer true and the while loop ends.


TOP | NEXT: do...while loops