Back to Blog
Lesson 9 of the PHP: Modern PHP from the Ground Up course
PHPJuly 27, 20263 min read

Iterating with For and While Loops in PHP: A Practical Guide

Learn how to use for and while loops in PHP to automate repetitive tasks. Master loop control with break and continue to write cleaner, more efficient code.

PHPprogrammingloopsiterationbackend developmentweb development
Detailed view of programming code in a dark theme on a computer screen.

Previously in this course, we explored Multidimensional Arrays to store complex data structures. Now that you can organize your data, you need a way to process it efficiently. This lesson introduces iteration, the process of executing a block of code multiple times, which is essential for any backend task ranging from generating table rows to processing database results.

The While Loop: Controlled Repetition

A while loop is the simplest form of iteration. It continues to execute a block of code as long as a specified condition evaluates to true. Think of it as an "if statement that repeats."

Basic Structure

PHP
$counter = 1;

while ($counter <= 5) {
    echo "Count is: $counter <br>";
    $counter++; #6A9955">// Crucial: modify the condition variable
}

In this example, the code inside the braces runs as long as $counter is 5 or less. The increment step $counter++ is vital; without it, the condition would never become false, resulting in an "infinite loop" that crashes your script.

The For Loop: Precise Iteration

Detailed view of programming code in a dark theme on a computer screen.

When you know exactly how many times you need to iterate—such as looping through a fixed number of items—the for loop is your best tool. It packs the initialization, condition, and increment into one line.

Syntax breakdown

PHP
#6A9955">// for (initialization; condition; increment)
for ($i = 0; $i < 10; $i++) {
    echo "Iteration number: $i <br>";
}
  1. Initialization: Executed once at the start ($i = 0).
  2. Condition: Checked before every iteration ($i < 10).
  3. Increment: Executed after every iteration ($i++).

Controlling Loops with Break and Continue

Sometimes, you need to exit a loop early or skip a specific iteration based on logic.

  • break: Immediately stops the loop execution.
  • continue: Skips the current iteration and jumps to the next one.

Worked Example: Filtering Data

Imagine we are processing a list of integers from a configuration file and we want to stop at the first negative number, while skipping zeros.

PHP
$numbers = [10, 5, 0, 8, -1, 3];

foreach ($numbers as $number) {
    if ($number === 0) {
        continue; #6A9955">// Skip zeros
    }
    
    if ($number < 0) {
        break; #6A9955">// Stop entirely if we hit a negative
    }
    
    echo "Processing value: $number <br>";
}

Hands-on Exercise

In our running MVC project, we often need to generate HTML lists for navigation. Create a script that uses a for loop to generate a list of 5 dynamic page links. Use an if statement inside your loop to add a CSS class active only when the loop reaches the index 2.

Common Pitfalls

  1. Infinite Loops: Always verify that your loop's condition will eventually be met. If you are using a while loop, ensure your counter or state variable is updated inside the loop body.
  2. Off-by-one errors: Beginners often confuse i < 5 with i <= 5. The former runs 5 times (0, 1, 2, 3, 4), while the latter runs 6 times (0, 1, 2, 3, 4, 5).
  3. Overusing Loops: If you find yourself writing complex, nested loops, consider if a built-in array function (like array_map or array_filter) might be more readable and performant.

FAQ

Q: When should I choose for over while? A: Use a for loop when you have a known range or count. Use while when you are waiting for a specific event or external state to change (e.g., reading a file line-by-line).

Q: Can I put a loop inside another loop? A: Yes, these are called nested loops. They are common when dealing with the Multidimensional Arrays we covered previously, but be careful with performance, as they increase execution time exponentially.

Recap

Iteration is the backbone of dynamic web applications. By mastering for and while loops, you can process data collections and automate repetitive output. Remember to always provide an exit condition for your loops and use break and continue to manage flow control cleanly.

Up next: Mastering Foreach Loops — the specialized, idiomatic way to handle arrays in PHP.

Similar Posts