Chapter 5

Loops and Repetition

Repetition is where a small mistake gets multiplied. Give every loop clear boundaries, state you can trace by hand, and a definite way out.

Chapter 5, Loops and Repetition

What you will learn

  • Use for, foreach, and while loops appropriately.
  • Trace loop variables and accumulators by hand.
  • Recognize off-by-one and infinite-loop defects.
  • Use break and continue sparingly and intentionally.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

5.1 Choosing the Right Loop

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$countdown = 3;

while ($countdown > 0) {
    echo $countdown . PHP_EOL;
    $countdown -= 1;
}

echo "Liftoff!" . PHP_EOL;

5.2 Counters, Accumulators, and Boundaries

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$items = ["a", "b", "c"];
$last = count($items) - 1;

echo "First index: 0" . PHP_EOL;
echo "Last index: " . $last . PHP_EOL;
echo $items[$last] . PHP_EOL;

5.3 Controlling Loop Flow

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$scores = [];

while (true) {
    echo "Score (or done): ";
    $line = trim(fgets(STDIN));

    if ($line === "done") {
        break;
    }

    if (!is_numeric($line)) {
        echo "Please enter a number." . PHP_EOL;
        continue;
    }

    $scores[] = (float) $line;
}

echo "Collected: " . count($scores) . PHP_EOL;

TPRM Lab 5.1: Count with for

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

for ($i = 1; $i <= 5; $i += 1) {
    echo $i . PHP_EOL;
}

TPRM Lab 5.2: Accumulate with foreach

Type this into a file, predict the output, then run it.

PHP
<?php

declare(strict_types=1);

$scores = [72, 88, 91, 64];
$total = 0;

foreach ($scores as $score) {
    $total += $score;
}

$average = $total / count($scores);
echo "Average: " . $average . PHP_EOL;

Back to PHP the TPRM Way