php · level 1 · unit 6 · lesson 3
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Every colour gets a turn. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$colours = ["red", "green", "blue"];
foreach ($colours as $colour) {
echo strtoupper($colour) . "\n";
}
your turn
Your turn. Add up your scores.
Type three scores from your last game, as integers. Run it and let the loop add them up for you.
fix it
These scores should add up to 20. Can you fix the total?
- The total comes out as 4, the last score. What happens to
$totalon each go? - Line 5 overwrites the total with the score, so the earlier scores are thrown away.
- Add the score to what is already there,
$total = $total + $score;, then press run.
nailed it
you made a loop walk through an array. :D
foreachvisits every item, from first to last.- On each go, the item variable holds the next item.
- A running total starts at 0 and grows inside the loop.
new words in your collection
- foreach
- running total
This lesson isn’t saved. A free account remembers every lesson you finish.