Skip to main content
PHP for Beginners
CHAPTER 08 Beginner

PHP Loops

Updated: May 12, 2026
20 min read

# Chapter 8: PHP Loops

1. Introduction

Welcome to Chapter 8! One of the greatest strengths of a computer is its ability to perform repetitive tasks incredibly fast without complaining. If you need to write "I will not throw paper in class" 100 times, you could write 100 echo statements. Or, you could write a loop! Loops execute a block of code a specified number of times, or as long as a certain condition remains true. In this chapter, we will learn about the while, do...while, for, and foreach loops.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use a while loop to execute code as long as a condition is true.
  • Use a for loop to execute code a specific number of times.
  • Understand how do...while guarantees at least one execution.
  • Briefly introduce the foreach loop (which we will master in the Arrays chapter).
  • Control loop flow using break and continue.

3. The while Loop

The while loop loops through a block of code as long as the specified condition evaluates to true.
php
12345678
<?php
$count = 1;

while ($count <= 5) {
    echo "The count is: $count <br>";
    $count++; // VERY IMPORTANT: Increment the counter, otherwise it runs forever!
}
?>

4. The do...while Loop

This loop will always execute the block of code at least once, and then it will repeat the loop as long as the specified condition is true. It evaluates the condition at the *end* of the loop, not the beginning.
php
123456789
<?php
$x = 10;

do {
    echo "The number is: $x <br>";
    $x++;
} while ($x <= 5);
// Output will be "The number is: 10" exactly once, because it checks the condition AFTER running.
?>

5. The for Loop

The for loop is best used when you know exactly in advance how many times the script should run. It packs the initialization, condition, and increment into a single neat line.
php
123456
<?php
// for (initialization; condition; increment)
for ($i = 1; $i <= 5; $i++) {
    echo "Current iteration: $i <br>";
}
?>

6. Controlling Loops: Break and Continue

Sometimes you need to interrupt a loop before it finishes naturally.
  • break: Exits the loop entirely immediately.
  • continue: Skips the rest of the current iteration and jumps straight to the next iteration.
php
123456789101112
<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i == 3) {
        continue; // Skips printing 3
    }
    if ($i == 8) {
        break; // Stops the loop entirely at 8
    }
    echo "Number: $i <br>";
}
// Outputs: 1, 2, 4, 5, 6, 7
?>

7. Real-World Examples

Imagine you are building a dropdown menu for a user's birth year on a registration form. Typing 100 <option> tags manually would be terrible. Let PHP do the heavy lifting!
php
12345678910
<select name="birth_year">
    <?php
    $current_year = date("Y"); // Gets the current year (e.g., 2026)
    
    // Loop backwards from current year down to 1900
    for ($year = $current_year; $year >= 1900; $year--) {
        echo "<option value=&#039;$year'>$year</option>";
    }
    ?>
</select>

8. Output Explanations

In the dropdown example, the for loop starts at 2026. The condition checks if $year >= 1900. Since it is, it outputs the <option> tag for 2026. Then $year-- subtracts 1, making it 2025. It repeats this process 127 times almost instantly, generating a complete HTML dropdown menu.

9. Common Mistakes

  • Infinite Loops: If you forget to update your counter variable (like forgetting $i++ in a while loop), the condition will ALWAYS be true. The loop will run forever until the server crashes or times out.
  • Off-by-One Errors: Using < 10 when you actually meant <= 10. If you want to run exactly 10 times starting from 1, you must use <=.
  • Misplacing semicolons: Writing for ($i=0; $i<5; $i++); { ... } (notice the semicolon before the brace). This breaks the loop syntax.

10. Best Practices

  • Use a for loop when you know the exact number of iterations.
  • Use a while loop when reading data from a file or a database where you don't know in advance how many rows exist.
  • Keep the logic inside your loops as lightweight as possible. Running complex database queries inside a loop 10,000 times will bring your server to a halt.

11. Exercises

  1. 1. Write a while loop that counts backwards from 10 to 1, and then echoes "Blastoff!".
  1. 2. Write a for loop that outputs only EVEN numbers between 1 and 20. (Hint: increment by 2, or use the % modulus operator).

12. Mini Project: Multiplication Table Generator

Task: Create an HTML table that displays the multiplication table for the number 7 using a loop.
php
123456789101112131415161718192021222324252627282930313233
<?php
$multiplier = 7;
?>
<!DOCTYPE html>
<html>
<head>
    <title>Multiplication Table</title>
    <style>
        table { border-collapse: collapse; width: 200px; }
        th, td { border: 1px solid black; padding: 8px; text-align: center; }
        th { background-color: #f2f2f2; }
    </style>
</head>
<body>
    <h2>Multiplication Table for <?php echo $multiplier; ?></h2>
    <table>
        <tr>
            <th>Calculation</th>
            <th>Result</th>
        </tr>
        <?php
        // Loop from 1 to 10
        for ($i = 1; $i <= 10; $i++) {
            $result = $multiplier * $i;
            echo "<tr>";
            echo "<td>$multiplier x $i</td>";
            echo "<td><strong>$result</strong></td>";
            echo "</tr>";
        }
        ?>
    </table>
</body>
</html>

13. Coding Challenges

Challenge 1: Use a while loop to sum up all the numbers from 1 to 50. Echo the final total.
php
123456789101112
<?php
// Solution
$i = 1;
$total = 0;

while ($i <= 50) {
    $total += $i;
    $i++;
}

echo "The total sum is: " . $total;
?>

14. MCQs with Answers

1. Which loop is guaranteed to execute its code block at least once? A) for loop B) while loop C) do...while loop D) infinite loop *Answer: C*

2. What causes an infinite loop? A) Using the break keyword. B) Forgetting to increment or change the condition variable so it never becomes false. C) Putting a loop inside another loop. D) Using continue. *Answer: B*

3. What does the continue statement do in a loop? A) Exits the loop entirely. B) Pauses the loop for 1 second. C) Restarts the loop from the very beginning. D) Skips the current iteration and jumps to the next iteration. *Answer: D*

15. Interview Questions

Q: What is the main difference between a for loop and a while loop? *A:* A for loop is typically used when the number of iterations is known before entering the loop, as the counter initialization, condition, and increment are all bundled together. A while loop is used when the number of iterations is unknown, and it runs strictly as long as a condition remains true (like reading file lines until the end of the file is reached).

Q: How does the foreach loop differ from the others? *A:* We will cover it deeply later, but foreach is specifically designed to iterate over arrays and objects. It automatically loops through every item in an array without needing a counter variable or an exit condition.

16. FAQs

Q: Can I put an if statement inside a loop? *A:* Yes! This is very common. You can nest loops inside loops, and if statements inside loops, to create highly complex logic structures.

17. Summary

You've unlocked automation! You learned how to use while and do...while loops for condition-based repetition, and for loops for counter-based repetition. You built dynamic HTML using loops and learned how to control loop flow using break and continue.

18. Next Chapter Recommendation

Our loops are powerful, but putting all our code in one long file gets messy fast. In Chapter 9: PHP Functions, we will learn how to wrap our code into reusable, organized blocks that we can call whenever we want!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·