Web Development /PHP Programming / Lesson
Web Development

Loops

Learn how PHP loops automate repetitive tasks using for, while, do...while, foreach, nested loops, loop control statements, practical iteration patterns, and safe techniques for processing data efficiently.

🎯

Learning Objectives

["Explain why loops are important in PHP programming.","Use for loops to repeat code a known number of times.","Use while loops when repetition depends on a condition.","Use do...while loops when code must execute at least once.","Use foreach loops to process arrays and iterable data.","Understand loop initialization, conditions, and updates.","Use break and continue to control loop execution.","Create nested loops for working with multidimensional data.","Avoid infinite loops and common iteration mistakes.","Apply loops to practical tasks such as calculations, lists, tables, and data processing."]

📖

Lesson Content

Introduction to PHP Loops

A loop allows PHP to execute the same block of code repeatedly without requiring the programmer to write the same instructions again and again.

Loops are useful whenever an application needs to process multiple items, repeat an operation, generate output, calculate values, search through data, or perform an action until a condition changes.

For example, instead of writing:

echo 1;
echo 2;
echo 3;
echo 4;
echo 5;

You can use a loop:

for ($number = 1; $number <= 5; $number++) {
    echo $number;
}

PHP provides several important loop structures:

  • for
  • while
  • do...while
  • foreach

1. The for Loop

The for loop is commonly used when you know how many times an operation should be repeated.

Basic structure:

for (initialization; condition; update) {
    // Code to repeat
}

Example:

for ($i = 1; $i <= 5; $i++) {
    echo $i . '<br>';
}

The loop performs three important tasks:

  1. Initializes the counter.
  2. Checks the condition.
  3. Updates the counter after each iteration.

The output is:

1
2
3
4
5

2. Understanding the for Loop Structure

Consider this loop:

for ($i = 1; $i <= 5; $i++) {
    echo $i;
}

The three sections mean:

  • $i = 1 — initialize the counter.
  • $i <= 5 — continue while the condition is true.
  • $i++ — increase the counter after each iteration.

The sequence is approximately:

$i = 1
Check condition
Execute body
Increase $i

$i = 2
Check condition
Execute body
Increase $i

...

When $i becomes 6, the condition becomes false and the loop stops.


3. Counting Backwards

A for loop can also count downward.

for ($i = 5; $i >= 1; $i--) {
    echo $i . '<br>';
}

The output is:

5
4
3
2
1

This is useful for countdowns and reverse iteration.


4. Changing the Step

The update expression does not have to increase the counter by exactly one.

for ($i = 0; $i <= 20; $i += 5) {
    echo $i . '<br>';
}

The output is:

0
5
10
15
20

This technique is useful when processing data in fixed increments.


5. The while Loop

The while loop repeatedly executes a block of code as long as its condition remains true.

Basic structure:

while (condition) {
    // Code to repeat
}

Example:

$number = 1;

while ($number <= 5) {
    echo $number . '<br>';
    $number++;
}

The loop continues until the condition becomes false.

Important Rule

A variable used in the condition should normally change during the loop. Otherwise, the loop may never end.

$number = 1;

while ($number <= 5) {
    echo $number;
    $number++;
}

Here, $number changes on every iteration.


6. The do…while Loop

The do...while loop is similar to while, but the code block executes at least once before the condition is checked.

Basic structure:

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

Example:

$number = 1;

do {
    echo $number;
    $number++;
} while ($number <= 5);

The output is:

12345

Difference Between while and do…while

Consider:

$number = 10;

while ($number < 5) {
    echo 'Hello';
}

The body does not execute because the condition is false from the beginning.

Now consider:

$number = 10;

do {
    echo 'Hello';
} while ($number < 5);

The message is printed once because a do...while loop always executes its body before checking the condition.


7. The foreach Loop

The foreach loop is designed for iterating over arrays and other iterable values.

Example:

$courses = array(
    'PHP',
    'JavaScript',
    'WordPress',
    'Data Analysis'
);

foreach ($courses as $course) {
    echo $course . '<br>';
}

The loop processes each item in the array.

This is one of the most commonly used loops in PHP applications.


8. foreach with Keys and Values

Associative arrays contain keys and values. A foreach loop can access both.

$student = array(
    'name' => 'Ade',
    'course' => 'Web Development',
    'level' => 'Beginner'
);

foreach ($student as $key => $value) {
    echo $key . ': ' . $value . '<br>';
}

The output will contain:

name: Ade
course: Web Development
level: Beginner

This pattern is extremely useful when processing database results, configuration arrays, form data, and API responses.


9. foreach and Array References

PHP allows a foreach loop to modify array values by using a reference.

$scores = array(50, 60, 70);

foreach ($scores as &$score) {
    $score += 5;
}

unset($score);

print_r($scores);

The unset($score) statement is recommended after a reference-based foreach loop so that the reference does not remain attached to the last array element.

Use references carefully because they can make code harder to reason about if used unnecessarily.


10. Looping Through Associative Data

Loops are especially useful when working with structured application data.

$students = array(
    array(
        'name' => 'Ade',
        'score' => 85
    ),
    array(
        'name' => 'John',
        'score' => 72
    ),
    array(
        'name' => 'Mary',
        'score' => 91
    )
);

foreach ($students as $student) {
    echo $student['name'] . ': ';
    echo $student['score'] . '<br>';
}

This pattern is common when processing records retrieved from a database.


11. Nested Loops

A nested loop is a loop inside another loop.

for ($row = 1; $row <= 3; $row++) {

    for ($column = 1; $column <= 3; $column++) {
        echo "Row {$row}, Column {$column}<br>";
    }

}

The inner loop runs completely for every iteration of the outer loop.

Nested loops are useful for multidimensional arrays, tables, grids, and other structured data.


12. Nested foreach Loops

Multidimensional arrays can also be processed using nested foreach loops.

$classes = array(
    'Web Development' => array(
        'HTML',
        'CSS',
        'JavaScript'
    ),
    'Data Analysis' => array(
        'Excel',
        'SQL',
        'Python'
    )
);

foreach ($classes as $class_name => $topics) {

    echo '<h3>' . $class_name . '</h3>';

    foreach ($topics as $topic) {
        echo $topic . '<br>';
    }
}

This approach can be used to display courses and their lessons, categories and products, departments and employees, or other hierarchical data.


13. The break Statement

The break statement immediately stops a loop.

for ($i = 1; $i <= 10; $i++) {

    if ($i === 6) {
        break;
    }

    echo $i . '<br>';
}

The output stops at 5 because the loop ends when $i reaches 6.

break is useful when a desired item has been found or when continuing the loop is no longer necessary.


14. The continue Statement

The continue statement skips the current iteration and moves to the next iteration.

for ($i = 1; $i <= 5; $i++) {

    if ($i === 3) {
        continue;
    }

    echo $i . '<br>';
}

The output is:

1
2
4
5

The number 3 is skipped.


15. break and continue in foreach

These statements can also be used with foreach.

break Example

$courses = array(
    'HTML',
    'CSS',
    'JavaScript',
    'PHP',
    'Python'
);

foreach ($courses as $course) {

    if ($course === 'PHP') {
        break;
    }

    echo $course . '<br>';
}

continue Example

$numbers = array(1, 2, 3, 4, 5);

foreach ($numbers as $number) {

    if ($number % 2 === 0) {
        continue;
    }

    echo $number . '<br>';
}

Only odd numbers are displayed.


16. Avoiding Infinite Loops

An infinite loop occurs when the loop’s condition never becomes false.

For example:

$number = 1;

while ($number <= 5) {
    echo $number;
}

This loop never changes $number, so its condition remains true.

The corrected version is:

$number = 1;

while ($number <= 5) {
    echo $number;
    $number++;
}

Always make sure that a loop has a realistic path toward termination.


17. Loop Conditions and User Input

Loops can process data submitted by users, but external data should be validated before it controls program flow.

$limit = (int) ($_GET['limit'] ?? 0);

if ($limit > 0 && $limit <= 100) {

    for ($i = 1; $i <= $limit; $i++) {
        echo $i . '<br>';
    }

} else {

    echo 'Please provide a valid limit.';

}

The validation prevents an unreasonable input from directly controlling an unrestricted loop.


18. Looping Through a Range

PHP provides the range() function for creating sequences of values that can then be processed with foreach.

$numbers = range(1, 5);

foreach ($numbers as $number) {
    echo $number . '<br>';
}

You can also specify a step:

$numbers = range(0, 20, 5);

foreach ($numbers as $number) {
    echo $number . '<br>';
}

This produces:

0
5
10
15
20

19. for Loop with Multiple Expressions

A for loop can contain multiple expressions in its initialization and update sections.

for ($i = 0, $j = 10; $i <= 5; $i++, $j--) {
    echo "i={$i}, j={$j}<br>";
}

This can be useful in specific algorithms, although simple loops are usually easier to maintain.


20. Looping Through Strings

A string can be accessed character by character using its numeric positions.

$word = 'PHP';

for ($i = 0; $i < strlen($word); $i++) {
    echo $word[$i] . '<br>';
}

This produces:

P
H
P

For more complex Unicode text processing, use appropriate multibyte string functions instead of assuming that every visible character occupies one byte.


21. Calculating a Total with a Loop

Loops can be used to calculate totals.

$prices = array(1000, 2500, 5000, 3000);

$total = 0;

foreach ($prices as $price) {
    $total += $price;
}

echo 'Total: ₦' . $total;

The loop adds each price to the running total.


22. Finding the Largest Value

A loop can be used to inspect values and identify the largest one.

$scores = array(65, 82, 91, 74, 88);

$highest = $scores[0];

foreach ($scores as $score) {

    if ($score > $highest) {
        $highest = $score;
    }

}

echo 'Highest score: ' . $highest;

This demonstrates how loops and conditional statements can work together.


23. Searching for a Value

Loops can search through data.

$courses = array(
    'HTML',
    'CSS',
    'JavaScript',
    'PHP',
    'Python'
);

$search = 'PHP';
$found = false;

foreach ($courses as $course) {

    if ($course === $search) {
        $found = true;
        break;
    }

}

if ($found) {
    echo 'Course found.';
} else {
    echo 'Course not found.';
}

The break statement prevents unnecessary iterations after the desired item has been found.


24. Generating an HTML Table with a Loop

PHP loops are frequently used to generate dynamic HTML.

<?php

$students = array(
    array(
        'name' => 'Ade',
        'score' => 85
    ),
    array(
        'name' => 'John',
        'score' => 72
    ),
    array(
        'name' => 'Mary',
        'score' => 91
    )
);

?>

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Score</th>
        </tr>
    </thead>

    <tbody>

        <?php foreach ($students as $student): ?>

            <tr>
                <td>
                    <?php echo htmlspecialchars($student['name'], ENT_QUOTES, 'UTF-8'); ?>
                </td>

                <td>
                    <?php echo (int) $student['score']; ?>
                </td>
            </tr>

        <?php endforeach; ?>

    </tbody>
</table>

When inserting external or user-controlled data into HTML, output should be escaped appropriately. This helps prevent cross-site scripting vulnerabilities.


25. Alternative foreach Syntax

PHP provides an alternative syntax that is particularly useful when mixing PHP with HTML templates.

<?php foreach ($courses as $course): ?>

    <li>
        <?php echo htmlspecialchars($course, ENT_QUOTES, 'UTF-8'); ?>
    </li>

<?php endforeach; ?>

The alternative syntax uses:

  • foreach (...): to start the loop.
  • endforeach; to close it.

This can make template code easier to read.


26. Looping Through Database Results

Loops are frequently used when processing records returned from a database.

A simplified example might look like:

$students = array(
    array(
        'name' => 'Ade',
        'course' => 'PHP'
    ),
    array(
        'name' => 'John',
        'course' => 'JavaScript'
    )
);

foreach ($students as $student) {
    echo $student['name'] . ' - ';
    echo $student['course'] . '<br>';
}

In real applications, database-specific APIs should be used correctly, queries should be prepared where appropriate, and retrieved values should be validated and escaped for their destination.


27. Nested Loops and Multidimensional Arrays

Consider a school timetable:

$timetable = array(
    'Monday' => array(
        'PHP',
        'HTML',
        'CSS'
    ),
    'Tuesday' => array(
        'JavaScript',
        'SQL',
        'WordPress'
    )
);

foreach ($timetable as $day => $subjects) {

    echo '<h3>' . $day . '</h3>';

    foreach ($subjects as $subject) {
        echo $subject . '<br>';
    }

}

The outer loop processes each day, while the inner loop processes the subjects assigned to that day.


28. Looping with Conditions

Loops and conditions are often used together.

$scores = array(45, 78, 62, 39, 91, 55);

foreach ($scores as $score) {

    if ($score >= 50) {
        echo $score . ' - Pass<br>';
    } else {
        echo $score . ' - Fail<br>';
    }

}

This pattern is useful for filtering, classification, validation, and data processing.


29. Skipping Invalid Data

The continue statement can be useful when invalid or unwanted values should be skipped.

$scores = array(80, 0, 75, -5, 92);

foreach ($scores as $score) {

    if ($score < 0) {
        continue;
    }

    echo 'Score: ' . $score . '<br>';
}

In production applications, validation should be more comprehensive than this example, but the pattern demonstrates how continue works.


30. Stopping After Finding a Match

When searching a large collection, there is no reason to continue processing after the desired value has been found.

$users = array(
    'Ade',
    'John',
    'Mary',
    'David'
);

$target = 'Mary';

foreach ($users as $user) {

    if ($user === $target) {
        echo 'User found.';
        break;
    }

}

Using break can avoid unnecessary work.


31. Loop Performance and Readability

Loops should be written with both correctness and readability in mind.

For example, avoid unnecessarily repeating expensive operations inside a loop.

Instead of repeatedly calculating a fixed value, calculate it once when practical:

$count = count($courses);

for ($i = 0; $i < $count; $i++) {
    echo $courses[$i] . '<br>';
}

For simple array iteration, however, foreach is usually clearer:

foreach ($courses as $course) {
    echo $course . '<br>';
}

Choose the loop structure that communicates the purpose of the code most clearly.


32. Common Loop Mistakes

Mistake 1: Forgetting to Update the Counter

$i = 1;

while ($i <= 10) {
    echo $i;
}

This can create an infinite loop because $i never changes.

Mistake 2: Incorrect Loop Boundary

for ($i = 0; $i < 5; $i++) {
    echo $i;
}

This prints values from 0 through 4. Understand whether your application needs < or <=.

Mistake 3: Modifying an Array Unexpectedly

Be careful when modifying arrays during iteration, especially when references are involved.

Mistake 4: Excessive Nesting

Deeply nested loops can become difficult to understand and may have significant performance costs.

Mistake 5: Processing Untrusted Limits

Do not allow user input to create an uncontrolled number of iterations.


33. Practical Mini Project: Student Score Report

<?php

$students = array(
    array(
        'name' => 'Ade',
        'score' => 85
    ),
    array(
        'name' => 'John',
        'score' => 46
    ),
    array(
        'name' => 'Mary',
        'score' => 72
    ),
    array(
        'name' => 'David',
        'score' => 91
    )
);

foreach ($students as $student) {

    $status = ($student['score'] >= 50)
        ? 'Pass'
        : 'Fail';

    echo $student['name']
        . ' - '
        . $student['score']
        . ' - '
        . $status
        . '<br>';
}

This example combines foreach, comparison, and the ternary operator.


34. Practical Mini Project: Shopping Cart Total

<?php

$cart = array(
    array(
        'name' => 'Keyboard',
        'price' => 15000,
        'quantity' => 2
    ),
    array(
        'name' => 'Mouse',
        'price' => 8000,
        'quantity' => 1
    ),
    array(
        'name' => 'USB Cable',
        'price' => 3000,
        'quantity' => 3
    )
);

$total = 0;

foreach ($cart as $item) {

    $item_total = $item['price'] * $item['quantity'];

    $total += $item_total;

    echo $item['name']
        . ': ₦'
        . $item_total
        . '<br>';
}

echo '<strong>Total: ₦' . $total . '</strong>';

This demonstrates how loops can process multiple records and perform calculations on each item.


35. Best Practices for PHP Loops

  • Choose the loop type that best matches the problem.
  • Use foreach when iterating through arrays or iterable data.
  • Use for when a counter-based iteration is appropriate.
  • Use while when repetition depends on a condition.
  • Use do...while when the body must execute at least once.
  • Make sure loop conditions eventually become false.
  • Use break when further processing is unnecessary.
  • Use continue when an individual iteration should be skipped.
  • Avoid unnecessary nested loops.
  • Validate user-controlled values that determine iteration limits.
  • Escape dynamic data appropriately when generating HTML.
  • Keep loop bodies focused and readable.

36. Lesson Summary

Loops are essential PHP tools for repeating operations and processing collections of data efficiently.

The for loop is useful when a counter controls the number of iterations. The while loop repeats while a condition remains true, while do...while guarantees that its body executes at least once.

The foreach loop is especially important when working with arrays and iterable data. It can process simple arrays, associative arrays, multidimensional arrays, and structured application data.

The break statement stops a loop, while continue skips the current iteration. Together with conditional statements, loops form the foundation of many real-world PHP applications.

Once you understand loops, you can automate repetitive tasks, process database records, generate dynamic HTML, calculate totals, search data, build reports, and prepare for more advanced PHP programming.

💻

Code Example

<?php

$students = array(
    array(
        'name' => 'Ade',
        'score' => 85
    ),
    array(
        'name' => 'John',
        'score' => 46
    ),
    array(
        'name' => 'Mary',
        'score' => 72
    ),
    array(
        'name' => 'David',
        'score' => 91
    )
);

foreach ($students as $student) {

    $status = ($student['score'] >= 50)
        ? 'Pass'
        : 'Fail';

    echo $student['name']
        . ' - '
        . $student['score']
        . ' - '
        . $status
        . '<br>';
}
⭐

Key Takeaways

["Loops allow PHP to repeat code without duplicating the same instructions.","The for loop is useful when iteration is controlled by a counter.","The while loop continues while its condition remains true.","The do...while loop always executes its body at least once.","The foreach loop is ideal for processing arrays and iterable data.","The break statement immediately terminates a loop.","The continue statement skips the current iteration and moves to the next one.","Nested loops are useful for multidimensional data but should be used carefully.","Loop conditions must be designed so that loops can eventually terminate.","Loops become especially powerful when combined with conditions, arrays, functions, and database results."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress