PHP Loops: For, While, Do-While, and Foreach (Step-by-Step Guide)

Loops in PHP are used to execute a block of code multiple times. They help in automating repetitive tasks like iterating through arrays or fetching database records.

1. What are Loops in PHP?

A loop allows a block of code to be executed repeatedly until a specific condition is met.

Types of Loops in PHP:

for – Runs a block of code a specific number of times
while – Runs a block of code as long as the condition is true
do-while – Runs the code at least once, then repeats while the condition is true
foreach – Used for iterating over arrays and objects

2. PHP For Loop

Syntax:

for (initialization; condition; increment/decrement) {
    // Code to execute
}
Example: Print Numbers 1 to 5
<?php
    for ($i = 1; $i <= 5; $i++) {
        echo "Number: $i <br>";
    }
?>

Output:

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

🔹 When to Use?

  • When the number of iterations is known beforehand
  • Best for working with counters

3. PHP While Loop

Syntax:

while (condition) {
    // Code to execute
}

Example: Print Numbers 1 to 5

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

🔹 When to Use?

  • When the number of iterations is unknown
  • Best for reading data from databases or files

4. PHP Do-While Loop

Syntax:

do {
    // Code to execute
} while (condition);

Example: Print Numbers 1 to 5

<?php
    $i = 1;
    do {
        echo "Number: $i <br>";
        $i++;
    } while ($i <= 5);
?>

🔹 Key Difference from while Loop:

  • The do-while loop runs at least once, even if the condition is false.

Example: When Condition is Initially False

<?php
    $x = 10;
    do {
        echo "This will run once even if the condition is false.";
    } while ($x < 5);
?>

Output:

This will run once even if the condition is false.

5. PHP Foreach Loop (For Arrays)

The foreach loop is specifically designed for iterating over arrays.

Syntax:

foreach ($array as $value) {
    // Code to execute
}

Example: Iterate Over an Indexed Array

<?php
    $fruits = ["Apple", "Banana", "Cherry"];

    foreach ($fruits as $fruit) {
        echo "Fruit: $fruit <br>";
    }
?>

Output:

Fruit: Apple Fruit: Banana Fruit: Cherry

Example: Iterate Over an Associative Array

<?php
    $person = ["name" => "John", "age" => 30, "city" => "New York"];

    foreach ($person as $key => $value) {
        echo "$key: $value <br>";
    }
?>

Output:

name: John age: 30 city: New York

🔹 When to Use?

  • When working with arrays or objects
  • Simplifies iterating over key-value pairs

6. Nested Loops in PHP

Loops can be nested inside each other to iterate through multi-dimensional arrays or tables.

Example: Nested For Loop (Multiplication Table)

<?php
    for ($i = 1; $i <= 3; $i++) {
        for ($j = 1; $j <= 3; $j++) {
            echo "($i, $j) ";
        }
        echo "<br>";
    }
?>

Output:

(1, 1) (1, 2) (1, 3) (2, 1) (2, 2) (2, 3) (3, 1) (3, 2) (3, 3)

7. Loop Control Statements in PHP

Break Statement (Exit the Loop)

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

Output:

Number: 1 Number: 2

Continue Statement (Skip Iteration)

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

Output:

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

8. Best Practices for Using Loops in PHP

✅ Use foreach for arrays (more readable than for)
✅ Always use break in infinite loops to prevent crashes
✅ Optimize loops by minimizing function calls inside conditions
✅ Use while loops for unknown iterations