PHP Tutorial · Control Flow · Lesson 16 of 38
PHP Loops
Repeat code with while, do-while, for and foreach.
while and do-while
<?php
$n = 1;
while ($n <= 3) {
echo "while: $n\n";
$n++;
}
$tries = 0;
do {
$tries++;
} while ($tries < 0);
echo "do-while ran $tries time(s)\n";
Output
while: 1 while: 2 while: 3 do-while ran 1 time(s)
for
<?php
for ($i = 10; $i > 0; $i -= 3) {
echo $i, " ";
}
echo "\n";
Output
10 7 4 1
foreach
foreach is the loop you'll use most — it walks over arrays, optionally with keys:
<?php
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
echo $fruit, "\n";
}
$prices = ["coffee" => 3.0, "tea" => 2.5];
foreach ($prices as $item => $price) {
printf("%s costs $%.2f\n", $item, $price);
}
foreach ([1, 2, 3, 4, 5, 6] as $n) {
if ($n % 2) continue;
if ($n > 4) break;
echo "even: $n\n";
}
Output
apple banana cherry coffee costs $3.00 tea costs $2.50 even: 2 even: 4
break exits a loop; continue skips to the next iteration. Modifying an array by reference in foreach ($arr as &$v) has a famous gotcha — see the foreach reference puzzle.
Test yourself
Which loop is designed for iterating over arrays?
forwhileforeachdo-while
Show answer
Answer: foreach
Practice next
- foreach by Reference Leftover · coding problem