PHP Tutorial - PHP while loop






PHP while loops executes a block of code for a given condition.

Syntax

The while loop has the following syntax.

while(condition is true){
  do the loop statement
}

Example

For example, this code will loop from 1 to 10, printing out values as it goes:


<?php
       $i = 1;
       while($i <= 10) {
               print "Number $i\n";
               $i = $i + 1;
       }
?>

The code above generates the following result.





Example 2

Here are the two most common types of infinite loops:

<?php
        while(1) {
                print "In loop!\n";
        }
?>

Example 3

Infinite while loop with break statement


<?php
    $count = 0; 

    while ( true ) { 
      $count++; 
      echo "I ' ve counted to: $count < br / > "; 
      if ( $count == 10 ) break; 
    }   
?>

The code above generates the following result.





PHP do while loop

The PHP do...while construct is similar to a while loop. The difference is that the do...while loop is executed at least once.

The do while loop has the following syntax.

do{
  loop body
}while(condition is true);

Consider the following piece of code:


<?php
        $i = 1;
        do {
                print "Number $i\n";
        } while ($i < 10);
?>

The code above generates the following result.

Example rewrite

In comparison, that same code could be written using a while loop:


<?php
        $i = 1;
        while ($i < 10) {
                print "Number $i\n";
        }
?>

The difference is that the while loop would output nothing, because it checks the value of $i before entering the loop. Therefore, do...while loops are always executed a minimum of once.

The code above generates the following result.