Topics Control Flow & Functions Loops: for, while, foreach, do-while
beginner 12 min read

Loops: for, while, foreach, do-while

Iterate through data with all PHP loop types.

For Loop

for (\$i = 0; \$i < 5; \$i++) {
echo \$i;
}

While Loop

\$i = 0;
while (\$i < 5) {
echo \$i++;
}

Do-While

\$i = 0;
do {
echo \$i++;
} while (\$i < 5);

Foreach

\$items = ["a", "b", "c"];
foreach (\$items as \$item) {
echo \$item;
}
foreach (\$items as \$key => \$value) {
echo "\$key: \$value";
}

Break & Continue

Use break N to break out of N levels. Use continue to skip to next iteration.

Examples

<?php
$colors = ['red', 'green', 'blue'];
foreach ($colors as $i => $c) {
    echo "$i: $c\n";
}

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.