PHP do-while loop

In the PHP while loop if the initial condition is false then it will not execute the inner code but in real life application sometimes we need to execute the inner code at least one time even the condition is false. To do this PHP provides do-while loop. So the general form of PHP do-while loop is

do{

 //The body

   }while(condition);
In each time the do-while loop first executes the body of the loop and then evaluates the condition. If the condition returns true then the loop will repeat otherwise the loop terminates.

PHP do-while example

Now take a look at an example based on PHP do-while condition.
<?php
$value=1;
do
{
    echo $value;
    $value++;
    }while(!$value==1);
?> 
In this code snippet at first it prints the value 1 though the condition is not true. After printing 1 then it checks the while condition. Now the while condition is false so that the loop will be terminated. Consider another example where the while condition returns true.
<?php
$value=10;
do
{
    echo $value."<br>";
    $value--;
    }while($value>0);
?>
Try to understand the output. I think you understand the PHP do-while loop.

Comments

Popular posts from this blog

How to show only month and year fields in android Date-picker?

How to construct a B+ tree with example

Conflict Serializability in database