php do-while loop



PHP do-while loop 

PHP do-while loop always execute block of code at least once, then check condition and repeat the loop as long as the condition is true. 

PHP do-while loop syntax

<?php
do

// block of code to be executed 

while(condition)
?>


In do-while loop first execute a block of code once an then check the condition, if condition is true as long as the code to be executed. 

Example of php do-while loop

<?php
$i=1;
do 
{
echo $i;
$i++;
}
while($i<=5)
?>

The output is:
12345

In above do-while example, first set variable $i=1, then execute do statement once and then check the while condition $i<=5, 

at initial $i=1 directly execute do code print $i. 
Then increment 1 to $i, 
now $i=2 the check while ($i<=5) condition is true, 
$i=3 condition is true, 
$i=4 condition is true,
$i=5 condition is true. 
When $i=6 the condition $i<=5 is not true as 6 is not less than or equal to 5. The do-while loop result  is : 12345

do-while example 

<?php
$i=5;
do
{
echo $i;
$i- -;
}
while($i>0)
?>

The output is: 54321

Example – PHP do-while loop

<?php
$name=”meera”;
$i=1;
do
{
echo “Hello “. $name . “<br/>”;
$i++;
}
while($i<=5)
?>

The output is:

Hello meera
Hello meera
Hello meera
Hello meera
Hello meera

PHP do-while loop example

<?php
$i=1;
$sum=0;
do
{
$sum=$sum+$i;
$i++;
} while($i<=5);
echo “The Sum of 1 to 5 =” . $sum;
?>

The output The Sum of 1 to 5 = 15

do-while loop Example

<?php
$i=1;
do
{
echo $i;
$i=$i+2;
}
while($i<=10)
?>
The output is : 13579

Example to display odd and even no of given number using do-while loop.

<?php
$even=””;
$odd=””;
$i=1;
do
{
if($i%2==0)
{
$even = $even . ” ” .$i ;
}
else
{
$odd = $odd . ” ” .$i;
}$i++;
}
while($i<=20);
echo “The Even no = ” . $even .”<br/>”;
echo “The Odd no = ” . $odd;?>

The output is :

The Even no = 2 4 6 8 10 12 14 16 18 20
The Odd no = 1 3 5 7 9 11 13 15 17 19

Leave a Reply

Your email address will not be published. Required fields are marked *