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
foreach ($langs as $lang)walks values; keys stay out of sight.$name => $scoreunpacks each pair of an associative array.&$scoremakes the loop variable a reference, so+= 5edits the array.unset($score)drops the leftover reference before it can bite.
Keywords and builtins used here
asechoforeachprint_rstrtoupperunset
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.
Step 3 of 3 in Control flow, step 6 of 27 in Language basics.