0
0
PHPprogramming~10 mins

Foreach loop for arrays in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Foreach loop for arrays
Start with array
Pick first element
Execute loop body with element
More elements?
YesPick next element
No +---> Back to Execute loop body
End loop
No +---> Back to Execute loop body
The foreach loop picks each element from the array one by one and runs the loop body using that element until all elements are processed.
Execution Sample
PHP
<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}
?>
This code loops through each fruit in the array and prints its name on a new line.
Execution Table
IterationCurrent Element ($fruit)ActionOutput
1"apple"Print $fruitapple
2"banana"Print $fruitbanana
3"cherry"Print $fruitcherry
--No more elements, exit loop-
💡 All elements processed, foreach loop ends
Variable Tracker
VariableStartAfter 1After 2After 3Final
$fruitundefined"apple""banana""cherry""cherry" (holds last value)
Key Moments - 3 Insights
Why does $fruit change each iteration?
Because foreach assigns the current array element to $fruit at each iteration, as shown in execution_table rows 1 to 3.
What happens after the last element is processed?
The loop stops and $fruit holds the value of the last element ("cherry"), as shown in the variable_tracker final value.
Can foreach modify the original array elements?
Not in this example because $fruit is a copy of each element. To modify, you need to use references (not shown here).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $fruit during iteration 2?
A"apple"
B"banana"
C"cherry"
Dundefined
💡 Hint
Check the 'Current Element ($fruit)' column at iteration 2 in the execution_table.
At which iteration does the foreach loop stop?
AAfter iteration 1
BAfter iteration 2
CAfter iteration 3
DIt never stops
💡 Hint
Look at the exit note and the last iteration row in the execution_table.
If the array had 5 elements, how many times would the loop body run?
A5 times
B3 times
C4 times
DDepends on the element values
💡 Hint
Each element in the array causes one loop iteration, as shown in the concept_flow and execution_table.
Concept Snapshot
foreach ($array as $value) {
    // code using $value
}

- Loops over each element in $array
- $value holds current element
- Runs loop body once per element
- Stops after last element
- Simple way to read arrays
Full Transcript
The foreach loop in PHP goes through each element of an array one by one. It assigns the current element to a variable, here called $fruit, and runs the code inside the loop using that variable. This continues until all elements have been used. In the example, the loop prints each fruit name on its own line. After the last element, the loop ends and the variable holds the value of the last element. This is a simple way to read all items in an array without needing to manage indexes manually.