Lesson contents

PHP — Traversing arrays with foreach

PHP foreach visits the values of an array in order. continue skips the rest of the current pass, while break ends the loop.

A simple example

Print the numbers 1 to 3

  1. Start with Start at 1
  2. Do this Visit 1, 2, 3
  3. Result 1 → 2 → 3
Each pass prints one number on its own line. After 3 the loop has no more values to visit.
lesson.php
<?php
for ($n = 1; $n <= 3; $n++) {
    echo $n, PHP_EOL;
}
Output
1
2
3
Advertisements

Stop at the end of a batch

foreach visits each value in an indexed array. continue skips one reading and break exits the loop. The accumulator is initialized outside the loop so it keeps its value.

Readings: 4, −1, 0, 7. End marker: 0. This batch totals: 4.
Find the end of a scanner batch

A scanner sends 4, then an invalid reading of −1, then the batch marker 0. Add 4, skip the invalid reading and stop at the marker. The later 7 belongs to the next batch.

Run the example

PHP 8 or later. Run these commands from the directory containing the example.

php lesson.php
lesson.php
<?php
declare(strict_types=1);

$total = 0;
foreach ([4, -1, 0, 7] as $reading) {
    if ($reading === 0) {
        break;
    }
    if ($reading < 0) {
        continue;
    }
    $total += $reading;
}
echo $total, PHP_EOL;
Output
4

Start the total at zero. Add 4, skip −1, and stop at 0. The final 7 belongs to a different batch, so the result is 4.

Use a counted for loop for indexed bins

Use an explicit counter when the position belongs in the result. The array below is a dense list with consecutive integer keys.

Bin 1: 3 items. Bin 2: Empty. Bin 3: 5 items.
Keep the printed bin numbers

Three supply bins contain 3, 0 and 5 items. Skip printing the empty middle bin but keep its position in the sequence. The last line must still refer to bin 3.

Run this example

Save this program as lesson.php and run it separately.

php lesson.php
lesson.php
<?php
declare(strict_types=1);

$bins = [3, 0, 5];
for ($i = 0, $n = count($bins); $i < $n; ++$i) {
    if ($bins[$i] > 0) {
        printf("bin %d: %d\n", $i + 1, $bins[$i]);
    }
}
Output
bin 1: 3
bin 3: 5

The second bin is empty. Its index still occupies a position, so the final bin keeps number 3.

Try it yourself

What changes if the input is 4, −1, 7, 0?

Check your answer

Both positive readings arrive before the sentinel. Their sum is 11. An empty sequence yields 0.

PHP language reference

Related tags

  • PHP
  • iteration
  • loop control
  • accumulators