Module 7: LoopsBeginner40 min read
PHP Loops (for, while, do-while, foreach) & Iteration Performance
Master for, while, do-while, and foreach loops, break/continue with numeric levels, reference pitfalls in foreach, and iteration complexity.
Key Takeaways & Core Concepts
- `foreach`: Idiomatic choice for PHP arrays and
Traversableobjects (foreach ($map as $key => $val)). - `for`: Known numeric ranges (
for ($i = 0; $i < $n; $i++)). - `while` / `do-while`: Unknown iteration counts (e.g., reading stream lines).
1. Choosing the Right Loop
- `foreach`: Idiomatic choice for PHP arrays and
Traversableobjects (foreach ($map as $key => $val)). - `for`: Known numeric ranges (
for ($i = 0; $i < $n; $i++)). - `while` / `do-while`: Unknown iteration counts (e.g., reading stream lines).
1. foreach Key-Value Iteration & Loop Control
1<?php
2$prices = ["Book" => 500, "Pen" => 20, "Bag" => 1200];
3foreach ($prices as $item => $cost) {
4 if ($cost < 50) continue;
5 echo "$item: Rs.$cost\n";
6}
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
6 lines
Note: Skips items under 50 using `continue` while iterating associative keys and values.
2. Critical `foreach` Reference Pitfall
If you use foreach ($arr as &$v), $v remains a reference to the last element after the loop! Always call unset($v); immediately after the loop.
Practice & AssessmentPHP Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)