Skip to content

The do while statement

In PHP, the do-while loop is similar to the while loop, but with one key difference: the do-while loop executes the block of code at least once, even if the condition is initially false. After the first iteration, the loop continues to execute as long as the specified condition is true. The syntax of the do-while loop is as follows:

do {

    // code to be executed

} while (condition);

  • The block of code inside the do statement is executed once before the condition is evaluated.
  • After the initial execution, the loop continues to execute as long as the condition evaluates to true.
  • If the condition evaluates to false after the first iteration, the loop terminates, and the execution continues with the statement immediately following the loop.

Example:

$counter = 1;

do {

    echo “Count: $counter <br>”;

    $counter++;

} while ($counter <= 5);

In this example:

  • We initialize a variable $counter with the value 1.
  • The block of code inside the do statement prints the current value of $counter along with the text “Count:”.
  • After printing, we increment the value of $counter by 1 using the increment operator ($counter++).
  • The loop continues to execute as long as the value of $counter is less than or equal to 5.
  • Even if the condition $counter <= 5 is initially false (which is not the case here), the block of code inside the do statement would still be executed at least once.

Note:

  • Use the do-while loop when you want to execute a block of code at least once, regardless of the condition being true or false initially.

Ensure that the condition in the do-while loop is updated within the loop to avoid infinite loops. Failure to update the condition may result in an infinite loop if the condition is always true.