0% complete

Loops · Lesson 2 of 6

do...while Loop

Run a block once before checking whether to repeat.

Lesson

A do...while loop evaluates its condition after the body, so it always runs at least once. This suits work that must happen before a continuation check, such as processing one item from a stream. Make sure the body updates the condition to avoid accidental infinite loops. The terminating semicolon after the while condition is part of the syntax. Further guidance Before running a loop, identify the value that changes and the condition that eventually stops it. Check empty collections and one-item collections as well as the normal case. Prefer foreach when iterating a collection, and keep early exits easy to understand. Practice task: Create a fresh example for do...while Loop. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.

Code examples

do...while Loop
PHP
$attempt = 0;
do {
    $attempt++;
} while ($attempt < 1);
echo $attempt;
Expected output
1

Key points

  • Run a block once before checking whether to repeat.
  • Identify the loop state and a clear termination condition.
  • Test empty and one-item inputs as well as the normal case.

Your learning progress

Finish this lesson

Optional practice

PHP playground

This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.

Execution is disabled. No code is sent to a server.