0
0
PHPprogramming~10 mins

Do-while loop execution model in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Do-while loop execution model
Start
Execute body
Check condition
Yes| No
Repeat
The do-while loop runs the code inside the loop first, then checks the condition. If true, it repeats; if false, it stops.
Execution Sample
PHP
<?php
$i = 1;
do {
  echo $i . " ";
  $i++;
} while ($i <= 3);
?>
This code prints numbers 1 to 3 using a do-while loop.
Execution Table
StepVariable iCondition ($i <= 3)ActionOutput
111 <= 3 is TruePrint 1, increment i to 21
222 <= 3 is TruePrint 2, increment i to 32
333 <= 3 is TruePrint 3, increment i to 43
444 <= 3 is FalseExit loop
💡 i reaches 4, condition 4 <= 3 is False, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i12344
Key Moments - 2 Insights
Why does the loop body run even when the condition is false initially?
Because in a do-while loop, the body runs first before the condition is checked, as shown in step 1 of the execution_table.
When does the loop stop running?
The loop stops when the condition becomes false, which happens at step 4 when i is 4 and 4 <= 3 is false.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of i at step 3?
A4
B2
C3
D1
💡 Hint
Check the 'Variable i' column at step 3 in the execution_table.
At which step does the condition become false and the loop stops?
AStep 2
BStep 4
CStep 3
DStep 1
💡 Hint
Look at the 'Condition' column in the execution_table where it says false.
If the initial value of i was 5, how many times would the loop body execute?
A1 time
B0 times
C3 times
DInfinite times
💡 Hint
Remember do-while runs the body once before checking condition, see concept_flow.
Concept Snapshot
do-while loop syntax in PHP:
do {
  // code to run
} while (condition);

Runs loop body first, then checks condition.
Repeats if condition true, stops if false.
Always runs at least once.
Full Transcript
A do-while loop in PHP runs the code inside the loop first, then checks the condition. If the condition is true, it repeats the loop. If false, it stops. This means the loop body always runs at least once, even if the condition is false initially. In the example, the variable i starts at 1. The loop prints i, then increases it by 1. It repeats while i is less than or equal to 3. When i becomes 4, the condition fails and the loop stops. This is shown step-by-step in the execution table and variable tracker.