0
0
PhpHow-ToBeginner · 3 min read

How to Use Do While Loop in PHP: Syntax and Examples

In PHP, a do while loop executes the code block once before checking the condition at the end of the loop. It repeats the block as long as the condition is true, ensuring the code runs at least one time.
📐

Syntax

The do while loop runs the code inside do { ... } first, then checks the while (condition);. If the condition is true, it repeats the loop. This guarantees the code runs at least once.

  • do: starts the loop block
  • code block: the statements to run
  • while(condition): checks if the loop should continue
  • semicolon: required after the while condition
php
do {
    // code to execute
} while (condition);
💻

Example

This example shows a do while loop that prints numbers from 1 to 5. It runs the code first, then checks if the number is less than or equal to 5 to continue.

php
<?php
$number = 1;
do {
    echo $number . "\n";
    $number++;
} while ($number <= 5);
?>
Output
1 2 3 4 5
⚠️

Common Pitfalls

Common mistakes include forgetting the semicolon after the while condition, which causes syntax errors. Another mistake is using a condition that never becomes false, causing an infinite loop.

Also, remember that the loop runs at least once, so if you want to skip the loop when the condition is false initially, do while is not suitable.

php
<?php
// Wrong: missing semicolon after while condition
// do {
//     echo "Hello";
// } while (false)  // Syntax error

// Correct:
do {
    echo "Hello\n";
} while (false);
?>
Output
Hello
📊

Quick Reference

  • The do while loop always runs the code block once before checking the condition.
  • Use it when you want the code to run at least once regardless of the condition.
  • Always end the while condition with a semicolon.
  • Be careful to avoid infinite loops by ensuring the condition will eventually become false.

Key Takeaways

The do while loop runs the code block first, then checks the condition to repeat.
Always put a semicolon after the while(condition) statement.
Use do while when you need the code to run at least once.
Avoid infinite loops by making sure the condition eventually becomes false.
If you want to skip the loop when the condition is false initially, use a while loop instead.