Python Loops: While, For & Foreach Traversal
Loops allow automated repetitive execution. Learn while, do-while, for counters, break/continue control, and the powerhouse foreach loop designed specifically for iterating over indexed arrays and key-value hash maps.
"A for loop is an odometer ticking off exact mile markers from 1 to 10. A foreach loop is an automated postal worker picking up every single letter in a delivery bag one by one until the bag is empty."
Deep Dive: How It Works
The foreach Loop: foreach ($items as $item) or foreach ($map as $key => $val) traverses any iterable.
By-Reference Iteration: foreach ($items as &$val) allows direct modification of elements in place (remember to unset($val) after loop!).
Jump Statements: break stops loop execution; continue skips immediately to the next iteration.
Syntax Blueprint
<?php
foreach ($users as $id => $name) {
echo "ID: {$id} => {$name}\n";
}Use foreach with $key => $value syntax to traverse array elements smoothly.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Leaving a reference variable bound after a foreach ($arr as &$v) loop.Why it happens: $v remains bound to the last element of $arr; subsequent assignments to $v will accidentally overwrite the last element.
How to fix: Always call unset($v) immediately following by-reference foreach loops.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Filter Even Numbers with Foreach
Declare an array $numbers = [1, 2, 3, 4, 5, 6].
Iterate using foreach and print each even number on a new line preceded by "Even: ".
Finished reading and practicing?
Mark this lesson as completed to update your course progress.