PHP While Loop

The while loop executes a block of code as long as the specified expression is true.

Diagram of loop do while:



Syntax of wile loop:

<?php
   while(expr)
   {
       // code to do

   }
?>

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 code, execution will not stop until the end. If the while expression is FALSE in the beginning, the code won't even be run once.

<?php

   $x = 0;

   while($x < 5)
   {
       echo ($x . ' ');
       $x ++ ;
   }
?>

In this example, as $x in the beginning is 0, the expression $x < 5 , is true, so the code inside the while loop was executed, and output the value of $x, then add 1 to the variable. The code will work as long as the variable is less than 5. And in output we get .

   0 1 2 3 4