PHP: While Loops

While Loop in PHP

PHP has support for both:

  1. While loop - a pre-test loop, like the for loop. However, while loops are a condition-controlled loop versus a count-controlled loop which the for loop is.
  2. Do ... While loop - a post-test loop, e.g. test condition is at end of loop. This means the loop will always run at least once.

Example: Simple while loop


	<?php
	  $y = 1;
	  while ($x < 6)
	  {
		 $y = $y + 2;
		 echo "<p>x equals $x, y equals $y.</p>";
		  $x++;
	   }
	?>
	

Run it now

Output:

  x equals 1, y equals 3.

  x equals 2, y equals 5.

  x equals 3, y equals 7.

  x equals 4, y equals 9.

  x equals 5, y equals 11.


Example: Simple while loop


	<?php
	  $x=0;
	  while ($x < 10)
	  {
		 if ($x % 2 == 0)
			 echo "<p>$x is an even number.</p>";
		 $x++;
	   }
	?>
	

Run it now


Example: Do .. While loop


	<?
	  $x=1;
	  do
		{
		 echo "<p>x is equal to $x.</p>";
		 $x++;
		} while ($x<5);
	?>
	

Run it now

Output:

  x is equal to 1.

  x is equal to 2.

  x is equal to 3.

  x is equal to 4.