while
Repeats as long as the condition is true.
PHP
<?php
$i = 1;
while ($i <= 5) {
echo $i . " ";
$i++;
}
// 1 2 3 4 5do...while
Same, but the body always runs at least once because the check happens at the end.
PHP
<?php
$i = 10;
do {
echo $i; // prints 10 even though the condition is false
$i++;
} while ($i <= 5);for
Best when you know the number of iterations up front.
PHP
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}The three parts are: initialise; condition; step.
foreach
The one you'll use most — it walks an array directly.
PHP
<?php
$books = ["Muna Madan", "Palpasa Cafe", "Seto Dharti"];
foreach ($books as $book) {
echo $book . "<br>";
}With keys:
PHP
<?php
$prices = ["Muna Madan" => 250, "Palpasa Cafe" => 480];
foreach ($prices as $title => $price) {
echo "$title costs NPR $price<br>";
}To modify the array while looping, take the value by reference with &:
PHP
<?php
$nums = [1, 2, 3];
foreach ($nums as &$n) {
$n *= 2;
}
unset($n); // ALWAYS unset after a reference foreach
print_r($nums); // [2, 4, 6]Forgetting that unset($n) is a classic PHP bug: $n stays bound to the
last element, so the next loop that reuses $n quietly corrupts your
array.
break and continue
PHP
<?php
foreach ($books as $book) {
if ($book === "") {
continue; // skip this one, keep looping
}
if ($book === "STOP") {
break; // exit the loop entirely
}
echo $book;
}Alternative syntax in templates
PHP
<ul>
<?php foreach ($books as $book): ?>
<li><?= htmlspecialchars($book) ?></li>
<?php endforeach; ?>
</ul>