PHP do while Loop

The do...while loop in PHP is similar to the while loop but with one key difference: it executes the block of code at least once before evaluating the condition. This is useful when you want the code block to run at least once regardless of whether the condition is initially true or false.


Syntax


do {
    // Code to be executed
} while (condition);


  • The do block will always execute once before checking the while condition.
  • After the block has executed, the condition is evaluated. If it is true, the code block will execute again. If false, the loop ends.
Example
<!DOCTYPE html>
<html>
<body>
<?php
$i = 0;

do {
echo "The value of i is: $i<br>";
$i++;
} while ($i < 5);
?>
</body>
</html>

Try it yourself

do...while with a Condition that is Initially False


  • $i starts at 5, so the while condition ($i < 5) is false.
  • Despite this, the code inside the do block runs once before checking the condition, printing "The value of i is: 5".


Example
<!DOCTYPE html>
<html>
<body>
<?php
$i = 5;

do {
echo "The value of i is: $i<br>";
$i++;
} while ($i < 5);
?>
</body>
</html>

Try it yourself


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.