CodeMIRAI
0 XP

Loops

2 min read 6 runnable examples Quiz included

for

PHP
<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Step $i\n";
}

$total = 0;
for ($n = 1; $n <= 100; $n++) {
    $total += $n;
}
echo "1 + 2 + ... + 100 = $total\n";

while and do-while

PHP
<?php
$balance = 1000;
$years = 0;
while ($balance < 2000) {
    $balance *= 1.08;       // 8% interest a year
    $years++;
}
printf("Doubled after %d years: %.2f\n", $years, $balance);

$tries = 0;
do {
    $roll = random_int(1, 6);
    $tries++;
} while ($roll !== 6);
echo "Rolled a 6 after $tries tries\n";

while checks first; do-while runs its body once before checking. random_int gives a random whole number, so your number of tries will differ.

foreach

PHP
<?php
$langs = ["PHP", "Python", "SQL"];
foreach ($langs as $lang) {
    echo "I'm learning $lang\n";
}

$prices = ["tea" => 20, "coffee" => 35, "juice" => 40];
foreach ($prices as $item => $price) {
    echo "$item costs $price\n";
}

foreach is the everyday loop in PHP. With $key => $value, you get both the key and the value of each element.

Changing elements by reference

PHP
<?php
$prices = [100, 250, 80];
foreach ($prices as &$p) {      // & makes $p an alias for each element
    $p *= 1.18;
}
unset($p);                      // break the link once you're done
print_r($prices);

Normally $p is a copy, so changing it does nothing to the array. With &$p, it is the element. Always unset it afterwards: the variable still points at the last element, and reusing $p later would quietly overwrite it. Often array_map is clearer anyway.

break and continue

PHP
<?php
foreach (range(1, 10) as $n) {
    if ($n % 2 === 0) continue;   // skip even numbers
    if ($n > 7) break;            // stop entirely
    echo "$n ";
}
echo "\n";

for ($row = 1; $row <= 3; $row++) {
    for ($col = 1; $col <= 3; $col++) {
        if ($row * $col === 4) break 2;    // leave BOTH loops
        echo "($row,$col) ";
    }
}
echo "\n";

range(1, 10) makes an array of the numbers 1 to 10. break 2 leaves two levels of loop at once.

Building HTML with a loop

PHP
<?php $courses = ["Python" => 64, "JavaScript" => 31, "PHP" => 15]; ?>
<ul>
<?php foreach ($courses as $name => $lessons): ?>
  <li><?= htmlspecialchars($name) ?>: <?= $lessons ?> lessons</li>
<?php endforeach; ?>
</ul>

foreach (...): and endforeach; are the template-friendly form, and htmlspecialchars makes sure any text that might contain < or & is shown safely. Most PHP pages are built exactly like this.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.