Difference between while and do while loop in PHP
while and do-while, both loops are used to execute a block of code repeatedly, but they differ in how they check the loop condition.
while loop :- The while loop checks the loop condition at the beginning of each iteration. If the condition is true, the loop continues to execute. If the condition is false, the loop terminates.
Here’s an example of how to use a while loop in PHP:
";
$i++;
}
?>
The do-while loop -: The do-while loop checks the loop condition at the end of each iteration. This means that the loop will always execute at least once, even if the condition is false.
Here’s an example of how to use a do-while loop in PHP:
";
$i++;
} while ($i <= 5);
?>
Difference between while and do while loop in PHP
while loop | do..while loop |
---|---|
In a while loop, the condition is checked first, and if it is true, the loop's block of code is executed. If the condition is false initially, the loop is skipped entirely. | In a do-while loop, the loop's block of code is executed first, and then the condition is checked. This guarantees that the loop runs at least once, regardless of the initial condition. |
It is also known as an entry-controlled loop. | It is also known as an exit-controlled loop. |
Syntax for while loop-: while(condition) { //loop body } | Syntax for do-while loop-: do{ //loop body } while(condition); |
The controlling condition appears at the beginning of the loop. | The controlling condition is present at the end of the loop. |
No semicolon is used as a part of syntax,while(condition). | Semicolon is used as part of syntax, while(condition); |
It follows a top-down approach. | It follows a bottom-up approach. |