pTutorial

New way to learn PHP

PHP 5 do while loop

Do while loop

A do while loop works same as while, except that the expression is evaluated at the end of each iteration.

  • Do while loop code block executed at least one time before checking the expression.
  • A do while loop is a modified version of the while loop.

Flow chart

ptutorial | php tutorial

Syntax

do {
<code to be executed>;
}
While ( $expression );
.

Since the brackets do not end the entire statement, a semicolon is needed at the end.

Example of do while loop

    
    <?php
    
    $myvar=0;   
    do
    {
    echo "Value of variable j is:". $myvar."
"; }while ($myvar==1); echo "Out of loop" ; ?>

In the above example, the condition is not true instead of that data in between do block will be executed and after that check the condition and loop terminated.


Another example of do while loop

        <?php
        
        $var=0;
            echo " Do while loop :
"; do { echo "hello do while loop
"; $var++; } while ($var < 10); ?>

Explanation

The body of do while will be executed one time, even condition is false.

.

In case of while condition checked first while in case of do while execute code block one time after that condition is checked.

Nested do while loop

Nested do while lop is nothing loop within loop is called nesting and this loop is called nested loop.

 
 <?php
 
$i=9;
$j=10;
do
{
	echo "First do while loop i=".$i."j=".$j;
	echo "<br>";

		do
	{
		$i++;
		echo "Second while i=".$i."j=".$j;
		echo "<br>";
	}while($j == 5);

}while($i == 10)

?>

Output

First do while loop i=9j=10
Second while i=10j=10
First do while loop i=10j=10
Second while i=11j=10

Compare while loop and do while loop.

Looping Difference
While Do While
It is a looping construct that will execute only if the test condition Is true. It is a looping construct that will execute at least one even if the test condition is false.
It is entry control loop. It is exit control loop.
It is used for implementing common looping situations. It is typically used for implementing menu based program where the menu is required to be printed at least once.

QUOTES OF THE DAY

Whenever man commits a crime,heaven finds a witness.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER