The do-while
loop in PHP is similar to the while
loop, but it ensures the code inside the loop runs at least once before checking the condition.
Syntax of a PHP Do-While Loop
<?php do { // Code to be executed } while (condition); ?>
📝 Example 1: Simple Do-While Loop
Prints numbers from 1 to 5.
<?php $i = 1; do { echo "Number: $i <br>"; $i++; } while ($i <= 5); ?>
📝 Example 2: Do-While Loop That Runs at Least Once
Executes at least once, even if the condition is false.
<?php $i = 10; do { echo "This will print once, even if condition is false. <br>"; } while ($i < 5); ?>
📝 Example 3: Do-While Loop with User Input
Keep asking for user input until they enter "exit" (Assuming input is simulated).
<?php do { $input = readline("Enter something (type 'exit' to stop): "); echo "You entered: $input <br>"; } while ($input != "exit"); ?>
🎯 When to Use a Do-While Loop?
- When you need the loop to execute at least once.
- When working with user input validation.
- For tasks requiring an initial execution before condition checking.
📝 Practice Time!
Modify the examples above and experiment with different conditions to understand how do-while loops work.