typestar

foreach loops in PHP

One loop, three shapes: values only, key with value, and by reference.

<?php
$langs = ["php", "ruby", "go"];
foreach ($langs as $lang) {
    echo strtoupper($lang), PHP_EOL;
}

$scores = ["ada" => 95, "grace" => 88];
foreach ($scores as $name => $score) {
    echo "$name scored $score\n";
}

// &$score writes back into the array; unset drops the reference
foreach ($scores as &$score) {
    $score += 5;
}
unset($score);
print_r($scores);

How it works

  1. foreach ($langs as $lang) walks values; keys stay out of sight.
  2. $name => $score unpacks each pair of an associative array.
  3. &$score makes the loop variable a reference, so += 5 edits the array.
  4. unset($score) drops the leftover reference before it can bite.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
357
Tokens
86
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 61 seconds.

Type this snippet

Step 3 of 3 in Control flow, step 6 of 27 in Language basics.

← Previous Next →

foreach loops in other languages