php · level 2 · unit 1 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
foreach can hand you each key and its value.
A key and the value it points to make a . Write foreach ($basket as $fruit => $amount) and the loop hands you a whole pair on every go: the key in $fruit and the value in $amount.
Running totals get a shortcut too. $total += $amount; means the same as $total = $total + $amount;. This kind of shortcut is called a .
-= takes away and stores the answer, and .= joins more text onto the end of a string. Leave out the => part and foreach hands you only the values, as in Level 1.
<?php
$basket = ["apples" => 3, "pears" => 2, "plums" => 5];
$total = 0;
foreach ($basket as $fruit => $amount) {
echo "$amount $fruit\n";
$total += $amount;
}
echo "$total pieces of fruit\n"; Name the two loop variables after what they hold, like $fruit => $amount, and the loop reads like a sentence.
guess first
A day out with £20. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
$money = 20;
$spent = ["lunch" => 6, "bus" => 3, "comic" => 4];
foreach ($spent as $thing => $cost) {
$money -= $cost;
}
echo "£$money left\n";
your turn
Your turn. Log a week of reading.
Type how many minutes you read on each day, as whole numbers. Run it and let the loop add them up.
fix it
The price list reads back to front. Can you fix it?
- It says
2 costs £tea. Which variable is holding the key, and which the value? - In
foreach, the variable before=>always gets the key, and the one after gets the value. - Swap them so line 3 says
foreach ($prices as $item => $price), then press run.
nailed it
you looped through every pair. :D
foreach ($array as $key => $value)gives you both.- The key comes before
=>, the value after it. +=,-=and.=change a variable and store it back.
new words in your collection
- key-value pair
- compound assignment
This lesson isn’t saved. A free account remembers every lesson you finish.