PHP - Looping with the while Statement

Introduction

The simplest type of loop to understand uses the while statement.

A while construct looks very similar to an if construct:

while (expression  ) {
            // Run this code
}
// More code here

The expression inside the parentheses is tested.

If it evaluates to true, the code block inside the braces is run.

Then the expression is tested again; if it's still true, the code block is run again, and so on.

If at any point the expression is false, the loop exits and execution continues with the line after the closing brace.

Demo

<?php
          $widgetsLeft = 10;/*w w  w  . j a  v  a 2 s  .  c  o  m*/
          
          while ( $widgetsLeft  >  0 ) {
             echo "print:";
             $widgetsLeft--;
             echo "done. There are $widgetsLeft widgets left. \n ";
          }

          echo "out";
?>

Result

First a variable, $widgetsLeft, is created to record the number of widgets ( 10 ).

Then the while loop works through the widgets, prints them one at a time and displaying the number of widgets remaining.

Once $widgetsLeft reaches 0, the expression inside the parentheses ( $widgetsLeft > 0 ) becomes false , and the loop exits.

Control is then passed to the echo() statement outside the loop.

Related Topic