BeginnerLesson 4 of 16
Loops: for, while, foreach – PHP
Repetition over numbers and arrays.
The classic for loop has a start, a condition and a step. For arrays, foreach is the first choice: it provides values and, optionally, the key.
<?php
for ($i = 0; $i < 3; $i++) {
echo "Round $i\n";
}
$fruechte = ["Apple", "Pear", "Cherry"];
foreach ($fruechte as $index => $frucht) {
echo ($index + 1) . ". " . strtoupper($frucht) . "\n";
}while checks before every pass, do ... while only afterwards (so it runs at least once). break ends the loop, continue jumps to the next round.
<?php
$n = 0;
while (true) {
$n++;
if ($n % 2 === 0) {
continue;
}
if ($n > 7) {
break;
}
echo $n, " "; // 1 3 5 7
}
echo "\n";
$versuche = 0;
do {
$versuche++;
} while ($versuche < 3);
echo $versuche, "\n"; // 3With nested arrays you can unpack directly (destructuring):
<?php
$ergebnisse = [["Ada", 90], ["Bob", 75]];
foreach ($ergebnisse as [$name, $punkte]) {
echo "$name: $punkte\n";
}
$konfig = ["host" => "localhost", "port" => 3306];
foreach ($konfig as $schluessel => $wert) {
echo "$schluessel=$wert\n";
}WarningWith
foreach ($arr as &$x) (reference), $x remains a reference to the last element after the loop. Call unset($x); afterwards, otherwise a further loop will accidentally overwrite values.