Loops
Loops help you repeat actions: count numbers, iterate arrays, read files line by line, paginate records, etc. In PHP you’ll use for, while, do…while, and foreach. You can also break or skip iterations, and use generators to stream data efficiently.
| Loop | Best for | Notes |
|---|---|---|
for | Known count/index iteration | All loop parts inline (init; condition; step) |
while | Repeat while condition true | Check before each iteration |
do…while | Run at least once | Check after iteration |
foreach | Arrays/Traversables | Safest & most readable for collections |
1) for
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Count: $i\n";
}
?>
Multiple expressions
<?php
for ($i=0, $j=10; $i<5; $i++, $j--) {
echo "$i $j\n";
}
?>
2) while
<?php
$n = 3;
while ($n > 0) {
echo "n=$n\n";
$n--;
}
?>
3) do…while (runs at least once)
<?php
$pwdOk = false;
do {
echo "Try login once\n";
} while ($pwdOk);
?>
4) foreach (arrays & traversables)
By value (default)
<?php
$nums = [10,20,30];
foreach ($nums as $n) {
echo $n; // 10 20 30
}
?>
With keys
<?php
$user = ["name"=>"Sonu", "age"=>25];
foreach ($user as $key => $value) {
echo "$key: $value\n";
}
?>
By reference (modifies original)
<?php
$arr = ["a", "b"];
foreach ($arr as &$v) {
$v = strtoupper($v);
}
// IMPORTANT: unset reference to avoid side-effects later
unset($v);
var_dump($arr); // ["A","B"]
?>
Warning: When using
& in foreach, always unset($v) afterwards to break the reference.5) break & continue
<?php
for ($i=1; $i<=10; $i++) {
if ($i == 3) continue; // skip 3
if ($i == 7) break; // stop at 6
echo $i;
}
?>
Breaking out of nested loops
Use numeric argument or labels to break multiple levels.
<?php
outer: for ($i=1; $i<=3; $i++) {
for ($j=1; $j<=3; $j++) {
if ($i*$j == 4) {
break 2; // break two levels
// or: break outer;
}
echo "$i,$j\n";
}
}
?>
6) Iteration Tips
- Prefer
foreachfor arrays/maps — clearer and safer than manual indexes. - When you need the index/key, use
foreach ($arr as $k => $v). - Need to modify original values? Use
&$vand rememberunset($v). - For large datasets, process in batches or use generators to reduce memory.
- Avoid changing the array you’re iterating over (push/pop) — iterate a copy or collect changes.
7) Generators with yield (memory friendly)
Generators let you iterate results one by one without building big arrays in memory.
<?php
function countUp($max) {
for ($i=1; $i<=$max; $i++) {
yield $i;
}
}
foreach (countUp(5) as $n) {
echo $n;
}
?>
Generator with keys
<?php
function lines($path) {
$h = fopen($path, 'r');
$i = 0;
while (($line = fgets($h)) !== false) {
yield $i++ => rtrim($line, "\r\n");
}
fclose($h);
}
foreach (lines('/path/to/file.txt') as $num => $text) {
echo ($num+1) . ": $text\n";
}
?>
8) Common Pitfalls
| Issue | Why it happens | Fix |
|---|---|---|
| Infinite loop | Condition never becomes false | Update loop variable or add a break guard |
| Modifying array while iterating | Push/pop affects iteration state | Iterate a copy or collect changes |
Forgot to unset($v) after reference foreach |
Reference leaks into next operations | unset($v) after loop |
| Slow loops over large data | Creating big arrays consumes RAM | Use generators or chunked queries |
Practice Tasks
- Use a
forloop to print the first 10 multiples of 7 on one line. - Given an array of prices, use
foreachby reference to add 18% GST to each item (thenunset($item)). - Write a
whileloop that reads a file line by line until EOF, counting lines that contain the word “PHP”. - Create a generator
rangeStep($start, $end, $step)and iterate it withforeach. - Use nested loops to print a 10×10 multiplication table; break both loops when the product exceeds 60.
Next: Continue with Functions (parameters, returns, default/variadic args, type hints, anonymous functions, closures, and best practices).