×

php · level 2 · unit 1 · lesson 2

  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

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.