PHP while loop

In this chapter you will learn:

  1. What is PHP while loop
  2. Syntax for while loop
  3. Example - while loop with integer counter
  4. Example - Infinite Loops
  5. Example - infinite while loop with break statement

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/* 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//  ja  v  a  2  s  .co  m
        while(1) {
                print "In loop!\n";
        }
?>

Example 3

Infinite while loop with break statement


<?php/*from  j ava  2 s. c  om*/
    $count = 0; 

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

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. What is a do while loop
  2. Syntax for do while loop
  3. Example - do while loop with integer counter
Home » PHP Tutorial » PHP Statements
PHP Code Blocks
PHP Comments
PHP if
PHP if else
PHP switch
PHP foreach
PHP while loop
PHP do while loop
PHP for loop
PHP break
PHP continue
PHP Mixed-Mode Processing
PHP include/require