PHP Do While Loop

by Hiroshi on June 21, 2008

in Do Loop, Do While Loop, Loops, PHP Basics

A “do while” loop is a slightly modified version of the while loop. A do-while loop first do’s and secondly checks the while condition!

PHP Do While Loop Structure

– Define
– Do
– Print
– Increment or decrement
– Condition

PHP Do While Loop Example

<?php
$num = 1;
do
{
echo $num;
$num = $num + 1;
$num++;
}
while($num < 10)
 
// Output: 13579
 
?>

Displaying the numbers from 1 to 10, with their squares

<?php
$count = 1;
do
{
  $square = $count * $count;
  echo "$count squared is $square <br />";
  $count++;
}
while ($count <= 10);
 
// Output:
// 1 squared is 1
// 2 squared is 4
// 3 squared is 9
// 4 squared is 16
// 5 squared is 25
// 6 squared is 36
// 7 squared is 49
// 8 squared is 64
// 9 squared is 81
// 10 squared is 100
?>

Related Posts

Previous post:

Next post: