You are currently viewing How to use do while loop in PHP
  • Post category:PHP

How to use do while loop in PHP

How to use do while loop in PHP

Learn How to use the do while loop in php. PHP engine executes the statements in a do-while loop at least once; and then repeatedly executes the statement in a do-while loop as long as the given conditional expression evaluates to true.

Syntax:

initialization;
do {
statement;
increment/ decrement;
} while(conditional expression); // condition is checked at the end of the loop

Note: There is no alternative syntax for do while loop.

Example:

<?php
$i=0;
do{
echo "Hello world", "<br/>";
$i++;
}while($i<5);
?>
  1. When the PHP engine executes the first line of the above code, it is understood that “i” need to create one variable called “i” and put the value inside it “0”.
  2. Then, it executes the do body, it is not checking any condition at the beginning. It just executes the do loop body at least one time. So, if the printing line is printed, then $”i++” will be executed.
  3. Then it checks the condition “$i<5”. If the condition is true, it executes the body once again otherwise it the loop will be terminated. So, here the condition is true until the “i=4”.

Leave a Reply