Lesson 5 โข Beginner
Loops ๐
Repeat code efficiently with for, while, do-while, and foreach โ PHP's most powerful and frequently used loop.
What You'll Learn in This Lesson
- โข For loop for counted iterations
- โข While and do-while for condition-based loops
- โข Foreach for iterating arrays (PHP's most-used loop)
- โข Break and continue to control loop flow
- โข Nested loops and real-world order processing examples
for loop is like saying "make exactly 100 widgets." A while loop is "keep making widgets until the material runs out." A foreach loop is "inspect every widget in this box."1๏ธโฃ Loop Types at a Glance
| Loop | Best For | Syntax |
|---|---|---|
| for | Known number of iterations | for ($i=0; $i<10; $i++) |
| while | Unknown iterations, check first | while ($condition) |
| do-while | Run at least once | do while ($cond) |
| foreach | Iterate arrays (most common!) | foreach ($arr as $v) |
Try It: Basic Loops
Practice for, while, do-while, and foreach loops with real examples
// PHP Loops (simulated in JavaScript)
console.log("=== For Loop ===");
console.log();
console.log("Syntax: for ($i = 0; $i < count; $i++) { ... }");
console.log();
// for loop โ when you know how many times to loop
for (let i = 1; i <= 5; i++) {
console.log(" Iteration " + i + ": " + "โญ".repeat(i));
}
console.log();
console.log("=== While Loop ===");
console.log();
console.log("Syntax: while ($condition) { ... }");
console.log("Use when you DON'T know how many iterations.");
console.log(
...Try It: Advanced Loops
Nested loops, break/continue, and a real-world order processing system
// Advanced Loop Patterns in PHP
console.log("=== Nested Loops: Multiplication Table ===");
console.log();
// Build a 5x5 multiplication table
let header = " ร |";
for (let i = 1; i <= 5; i++) header += (" " + i).slice(-3);
console.log(header);
console.log(" โโโผโโโโโโโโโโโโโโโ");
for (let i = 1; i <= 5; i++) {
let row = (" " + i).slice(-2) + " |";
for (let j = 1; j <= 5; j++) {
row += (" " + (i * j)).slice(-3);
}
console.log(row);
}
console.log();
console.log("===
...โ ๏ธ Common Mistakes
<= vs <. Decide: do you start at 0 or 1?foreach for arrays in PHP โ it's faster, cleaner, and less error-prone than for with index.๐ Quick Reference โ PHP Loops
| Statement | Purpose |
|---|---|
| for ($i=0; $i<n; $i++) | Loop n times |
| foreach ($arr as $v) | Iterate values |
| foreach ($arr as $k=>$v) | Iterate key-value pairs |
| break | Exit loop immediately |
| continue | Skip to next iteration |
๐ Lesson Complete!
You've mastered PHP loops! Next, learn how to write reusable functions.
Sign up for free to track which lessons you've completed and get learning reminders.