your image

PHP do while loop - javatpoint

javapoint
Related Topic
:- PHP computer programming Java

PHP do-while loop

PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while loop is guaranteed to run at least once.

The PHP do-while loop is used to execute a set of code of the program several times. If you have to execute the loop at least once and the number of iterations is not even fixed, it is recommended to use the do-while loop.

It executes the code at least one time always because the condition is checked after executing the code.

The do-while loop is very much similar to the while loop except the condition check. The main difference between both loops is that while loop checks the condition at the beginning, whereas do-while loop checks the condition at the end of the loop.

 

C++ vs Java

Syntax

  1. do{  
  2. //code to be executed  
  3. }while(condition);  

Flowchart

Example

  1. <?php    
  2. $n=1;    
  3. do{    
  4. echo "$n<br/>";    
  5. $n++;    
  6. }while($n<=10);    
  7. ?>    

Output:

12345678910

Example

A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-while loop, it is must that the program should not contain any other statements after the do-while loop. In this case, it will not generate any error.

  1.  <?php  
  2.     $x = 5;  
  3.     do {  
  4.         echo "Welcome to javatpoint! </br>";  
  5.         $x++;  
  6.     } while ($x < 10);  
  7. ?>  

Output:

Welcome to javatpoint!Welcome to javatpoint!Welcome to javatpoint!Welcome to javatpoint!Welcome to javatpoint!

Example

The following example will increment the value of $x at least once. Because the given condition is false.

  1.  <?php  
  2.     $x = 1;  
  3.     do {  
  4.         echo "1 is not greater than 10.";  
  5.         echo "</br>";  
  6.         $x++;  
  7.     } while ($x > 10);  
  8.     echo $x;  
  9. ?>  

Output:

1 is not greater than 10.2

Difference between while and do-while loop

while Loopdo-while loopThe while loop is also named as entry control loop.The do-while loop is also named as exit control loop.The body of the loop does not execute if the condition is false.The body of the loop executes at least once, even if the condition is false.Condition checks first, and then block of statements executes.Block of statements executes first and then condition checks.This loop does not use a semicolon to terminate the loop.Do-while loop use semicolon to terminate the loop.

Comments