0
0
PHPprogramming~10 mins

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

Choose your learning style9 modes available
Concept Flow - While loop execution model
Initialize variable
Check condition
|Yes
Execute loop body
Update variable
Back to Check condition
Exit loop
Back to Check condition
The while loop starts by checking a condition. If true, it runs the loop body, updates variables, then checks the condition again. It stops when the condition is false.
Execution Sample
PHP
<?php
$i = 1;
while ($i <= 3) {
    echo $i . " ";
    $i++;
}
?>
This code prints numbers 1 to 3 using a while loop that runs while $i is less than or equal to 3.
Execution Table
StepVariable $iCondition ($i <= 3)ActionOutput
11TruePrint 1, increment $i to 21
22TruePrint 2, increment $i to 32
33TruePrint 3, increment $i to 43
44FalseExit loop
💡 $i is 4, condition 4 <= 3 is False, loop stops
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
$i12344
Key Moments - 2 Insights
Why does the loop stop when $i is 4?
Because the condition $i <= 3 becomes false at step 4, so the loop exits as shown in the execution_table row 4.
When is the variable $i incremented in the loop?
The variable $i is incremented after printing, inside the loop body, as seen in the 'Action' column of the execution_table rows 1 to 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of $i at Step 3?
A2
B4
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 4
BStep 3
CStep 2
DStep 1
💡 Hint
Look at the 'Condition' column in the execution_table to find when it is false.
If we start $i at 0 instead of 1, how many times will the loop run?
A3 times
B4 times
C2 times
D1 time
💡 Hint
Refer to variable_tracker and consider the condition $i <= 3 starting from 0.
Concept Snapshot
while (condition) {
  // code to run
  // update variables
}

- Checks condition before each loop
- Runs loop body only if condition is true
- Stops when condition is false
- Update variables inside loop to avoid infinite loop
Full Transcript
This example shows how a while loop works in PHP. We start with a variable $i set to 1. The loop checks if $i is less than or equal to 3. If yes, it prints $i and then increases $i by 1. This repeats until $i becomes 4, when the condition fails and the loop stops. The execution table tracks each step, showing variable values, condition results, actions, and output. The variable tracker shows how $i changes after each step. Key moments explain why the loop stops and when $i is incremented. The quiz asks about variable values and loop behavior based on the tables. The snapshot summarizes the while loop syntax and rules.