×

php · level 1 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A loop visits every item in an array.

foreach walks through an array one item at a time, from the first to the last. You need no counter, and it never runs past the end.

foreach ($coins as $coin) reads as: for each item in $coins, call it $coin and run the block. On every go, $coin holds the next item.

To add them all up, keep a . Start it at 0 before the loop, then add each item to it inside the block.

<?php
$coins = [2, 5, 1];
$total = 0;
foreach ($coins as $coin) {
    echo "Found £$coin\n";
    $total = $total + $coin;
}
echo "The jar holds £$total\n";

Pick names that read well together, like $coins for the array and $coin for one item.