PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

"while" Statement Examples

This section provides a tutorial example on how to use 'while' statements to repeat execution of one or more statements while a specified condition is true.

To help us understand how "while" statements work, I wrote the following the tutorial example PHP script:

<?php # WhileStatements.php
# Copyright (c) 2003 by Dr. Herong Yang. http://www.herongyang.com/
#
   $upperLimit = 20;
#
   print("\n Single-statement \"while\":\n");
   $sum = 0; $i = 0;
   while ($i<$upperLimit) $sum += ++$i;
   print("    Sum of 1 to 20: $sum\n");
#
   print("\n Multi-statement \"while\":\n");
   $i = 3;
   while ($i<$upperLimit) {
      $isPrime = true;
      $j = 2;
      while ($j<$i) {
         $isPrime = $i%$j > 0;
         if (!$isPrime) break;
         $j++;
      }
      if ($isPrime) print "   $i is a prime number.\n";
      $i++;
   }
#
   print("\n Multi-statement \"while ... endwhile\":\n");
   $i = 3;
   while ($i<$upperLimit):
      $isPrime = true;
      $j = 2;
      while ($j<$i):
         $isPrime = $i%$j > 0;
         if (!$isPrime) break;
         $j++;
      endwhile;
      if ($isPrime) print "   $i is a prime number.\n";
      $i++;
   endwhile;
?>

If you run this sample script, you should get:

 Single-statement "while":
    Sum of 1 to 20: 210

 Multi-statement "while":
   3 is a prime number.
   5 is a prime number.
   7 is a prime number.
   11 is a prime number.
   13 is a prime number.
   17 is a prime number.
   19 is a prime number.

 Multi-statement "while ... endwhile":
   3 is a prime number.
   5 is a prime number.
   7 is a prime number.
   11 is a prime number.
   13 is a prime number.
   17 is a prime number.
   19 is a prime number.

Last update: 2005.

Sections in This Chapter

"while" Statements

"while" Statement Examples

"for" Statements

"for" Statement Examples

"do ... while" Statements

"break" and "continue" Statements

Dr. Herong Yang, updated in 2009
"while" Statement Examples