0
0
PHPprogramming~10 mins

For loop execution model in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop execution model
Initialize i=0
Check: i < 3?
NoEXIT
Yes
Execute body: print i
Update: i = i+1
Back to Check
The loop starts by setting i to 0, then checks if i is less than 3. If yes, it runs the loop body, then increases i by 1 and repeats. If no, it stops.
Execution Sample
PHP
<?php
for ($i = 0; $i < 3; $i++) {
    echo $i . "\n";
}
?>
This PHP code prints numbers 0, 1, and 2 each on a new line using a for loop.
Execution Table
Iterationi before conditionCondition (i < 3)Body executedOutputi after update
10TrueYes01
21TrueYes12
32TrueYes23
43FalseNo
💡 i reaches 3, condition 3 < 3 is False, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3Final
i01233
Key Moments - 3 Insights
Why does the loop stop when i equals 3?
Because the condition i < 3 becomes False at iteration 4 (see execution_table row 4), so the loop does not run the body again.
When is the variable i updated in the loop?
i is updated after the loop body executes each time (see execution_table column 'i after update'), before the next condition check.
What is printed during each iteration?
The current value of i before it is incremented is printed (see execution_table 'Output' column for iterations 1 to 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i before the condition check in iteration 3?
A3
B2
C1
D0
💡 Hint
Check the 'i before condition' column in row 3 of the execution_table.
At which iteration does the loop condition become false?
AIteration 4
BIteration 1
CIteration 3
DIteration 2
💡 Hint
Look at the 'Condition (i < 3)' column and find where it is False.
If the loop condition changed to i < 2, how many times would the loop body execute?
A3 times
B1 time
C2 times
D0 times
💡 Hint
Refer to the variable_tracker and execution_table to see how condition affects iterations.
Concept Snapshot
PHP for loop syntax:
for (initialization; condition; update) {
  // code to run
}

Loop runs while condition is true.
Initialization runs once at start.
Update runs after each loop body execution.
Loop stops when condition is false.
Full Transcript
This visual execution model shows how a PHP for loop works step-by-step. The loop starts by setting i to 0. Then it checks if i is less than 3. If yes, it runs the loop body which prints i, then increases i by 1. This repeats until i reaches 3, when the condition becomes false and the loop stops. The execution table tracks each iteration's variable values, condition results, and outputs. The variable tracker shows how i changes from 0 to 3. Key moments clarify why the loop stops at 3 and when i updates. The quiz tests understanding of variable values and loop behavior. This helps beginners see exactly how the for loop runs in PHP.