Loops in PHP

Loops in PHP allow you to execute a block of code repeatedly, based on a condition. PHP supports multiple types of loops: for, while, do-while, and foreach. Let's explore each type.

The for Loop

The for loop is ideal for running a block of code a specific number of times:

<?php
    for ($i = 1; $i <= 5; $i++) {
        echo "Iteration: $i <br>";
    }
    ?>

Output:

Iteration: 1
    Iteration: 2
    Iteration: 3
    Iteration: 4
    Iteration: 5

The while Loop

The while loop executes as long as its condition is true:

<?php
    $count = 1;
    while ($count <= 3) {
        echo "Count is: $count <br>";
        $count++;
    }
    ?>

Output:

Count is: 1
    Count is: 2
    Count is: 3

The do-while Loop

The do-while loop executes the block of code at least once, even if the condition is false:

<?php
    $count = 1;
    do {
        echo "Count is: $count <br>";
        $count++;
    } while ($count <= 3);
    ?>

Output:

Count is: 1
    Count is: 2
    Count is: 3

The foreach Loop

The foreach loop is specifically designed for iterating over arrays:

<?php
    $fruits = ["apple", "banana", "cherry"];
    foreach ($fruits as $fruit) {
        echo "Fruit: $fruit <br>";
    }
    ?>

Output:

Fruit: apple
    Fruit: banana
    Fruit: cherry

Using break and continue

Use break to exit a loop prematurely and continue to skip to the next iteration:

<?php
    for ($i = 1; $i <= 5; $i++) {
        if ($i == 3) {
            break; // Exit the loop
        }
        echo "Number: $i <br>";
    }
    ?>

Output:

Number: 1
    Number: 2
<?php
    for ($i = 1; $i <= 5; $i++) {
        if ($i == 3) {
            continue; // Skip the current iteration
        }
        echo "Number: $i <br>";
    }
    ?>

Output:

Number: 1
    Number: 2
    Number: 4
    Number: 5

Next Steps

Experiment with each type of loop to understand when and where to use them. Mastering loops will allow you to handle repetitive tasks efficiently in your PHP applications. You can use loops inside functions!