Skip to content
Loops
step 1/5

Reading — step 1 of 5

Learn

~1 min readControl Flow
for ($i = 0; $i < 5; $i++) {
    echo $i, "\n";
}

$n = 16;
while ($n > 1) $n /= 2;

do {
    $x = readNext();
} while ($x > 0);

// foreach — most idiomatic for arrays
foreach ([10, 20, 30] as $v) {
    echo $v, "\n";
}
foreach (["a" => 1, "b" => 2] as $key => $value) {
    echo "$key => $value\n";
}

foreach is the workhorse for iterating arrays. The two-variable form as $key => $value gives you both pieces.

break exits the loop; continue skips to the next iteration. Both accept an optional level: break 2; breaks out of two nested loops.

For functional-style iteration, PHP has array_map, array_filter, array_reduce — covered in the collections chapter.

Typing tip: => (the arrow in foreach ($arr as $key => $value)) is an equals sign followed immediately by a greater-than sign — two keystrokes, no space. Not to be confused with ->, which is a hyphen then greater-than, used for object access.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…

Loops — PHP Fundamentals