Loops & Control Flow

🐘 PHP Lesson 5 Beginner

Loops execute statements repeatedly while a condition is satisfied. PHP supports standard numeric loops and a key-value foreach iteration loop.

1 foreach loops over collections

While PHP supports standard `while` and `for` loops, iterating over lists is typically done using the **`foreach`** loop: `foreach ($arr as $val)` or `foreach ($arr as $key => $val)` for associative arrays.

2 Loops Code

Let's run a program illustrating loops, continue statements, and break constraints:

PHP — Loops ▶ Run Code
<?php
echo "For loop count: ";
for ($i = 1; $i <= 5; $i++) {
    echo $i . " ";
}
echo "\n";

// While loop with continue/break
echo "While sequence (skipping 3, breaking at 6): ";
$count = 1;
while ($count <= 10) {
    if ($count == 3) {
        $count++;
        continue; // Skip the rest of this loop iteration
    }
    if ($count == 6) {
        break; // Exit the loop entirely
    }
    echo $count . " ";
    $count++;
}
echo "\n";
?>
3 Code Challenge
Challenge: Write a loop that sums all odd numbers between 1 and 25. Skip the number 13 using the `continue` keyword, and print the computed sum at the end.