0% complete

Loops · Lesson 1 of 6

while Loop

Repeat a block while a condition remains true.

Lesson

A while loop checks its condition before each iteration, so its body may run zero times. Change the state used by the condition on every intended path; otherwise the loop can run forever. Use a clear termination condition and a safety limit when processing external data. This counter moves toward its stopping value once per iteration. 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 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

while Loop
PHP
$count = 1;
while ($count <= 3) {
    echo $count, ' ';
    $count++;
}
Expected output
1 2 3 

Key points

  • Repeat a block while a condition remains true.
  • 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.