PHP while loop

Description

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//www .  j a v a  2 s .c  o  m
       $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/*  ww w  .  j a v a2s  . c  o  m*/
        while(1) {
                print "In loop!\n";
        }
?>

Example 3

Infinite while loop with break statement


<?php//from ww w  . jav  a 2s  .c o  m
    $count = 0; 

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

The code above generates the following result.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition