Paramclasses Academy - Blog

Tutorials Details

Loops in PHP (For, While, Do-While, and Foreach)

Loops in PHP (For, While, Do-While, and Foreach)

October 9, 2026

Core PHP Tutorial – Module 5:

Meta Title: Core PHP Module 5: Loops in PHP for Beginners

Meta Description: Learn PHP loops from scratch with simple examples of for, while, do-while, and foreach loops, including syntax, outputs, common mistakes, and practice exercises.

SEO Keywords: PHP loops, loops in PHP, PHP for loop, PHP while loop, PHP do while loop, PHP foreach loop, Core PHP tutorial, PHP for beginners

URL Slug: core-php-module-5-loops-in-php

Introduction to Loops in PHP

In PHP programming, loops are used to execute a block of code repeatedly as long as a specified condition is satisfied.

Imagine you want to print the numbers from 1 to 100. Writing 100 separate echo statements would take a lot of time. Instead, you can use a loop to perform the task with just a few lines of code.

Loops make programs shorter, easier to maintain, and more efficient.

In this module, you will learn:

  • What loops are in PHP

  • Types of loops in PHP

  • How to use for, while, and do-while loops

  • How to iterate through arrays using foreach

  • The difference between break and continue

  • Common loop mistakes and practical examples

1. What Is a Loop in PHP?

A loop is a programming structure that executes a block of code repeatedly.

For example, the following code prints “Hello PHP” three times:

<?php
echo "Hello PHP<br>";
echo "Hello PHP<br>";
echo "Hello PHP<br>";
?>

Output:

Hello PHP
Hello PHP
Hello PHP

You can achieve the same result using a loop:

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

Output:

Hello PHP
Hello PHP
Hello PHP

The loop reduces repetitive code and makes it easier to change the number of repetitions.

2. Types of Loops in PHP

PHP provides four commonly used loop structures:

  1. for loop – Used when you know how many times a block should repeat.

  2. while loop – Repeats while a condition is true.

  3. do-while loop – Executes the code at least once before checking the condition.

  4. foreach loop – Used to iterate through arrays and their elements.

Let's understand each loop with syntax and examples.

3. For Loop in PHP

The for loop is useful when you know how many times you want to execute a block of code.

Syntax

for (initialization; condition; increment_or_decrement) {
    // Code to execute
}

The three parts are:

  • Initialization: Sets the starting value.

  • Condition: Determines whether the loop should continue.

  • Increment or decrement: Updates the loop variable after each iteration.

Example 1: Print Numbers from 1 to 5

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

Output:

1
2
3
4
5

Explanation:

  • $i = 1 starts the loop at 1.

  • $i <= 5 keeps the loop running while $i is less than or equal to 5.

  • $i++ increases $i by 1 after every iteration.

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

Example 2: Print Even Numbers from 2 to 10

<?php
for ($i = 2; $i <= 10; $i += 2) {
    echo $i . "<br>";
}
?>

Output:

2
4
6
8
10

Here, $i += 2 increases the variable by 2 each time.

Example 3: Calculate the Sum of Numbers from 1 to 5

<?php
$sum = 0;

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

echo "Total Sum: " . $sum;
?>

Output:

Total Sum: 15

The loop adds 1, 2, 3, 4, and 5 to $sum.

4. While Loop in PHP

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

It is useful when the number of iterations is not necessarily known in advance.

Syntax

while (condition) {
    // Code to execute
}

Example 1: Print Numbers from 1 to 5

<?php
$i = 1;

while ($i <= 5) {
    echo $i . "<br>";
    $i++;
}
?>

Output:

1
2
3
4
5

Explanation:

  1. The variable $i starts at 1.

  2. PHP checks whether $i <= 5.

  3. If the condition is true, the number is printed.

  4. $i++ increases the value.

  5. The condition is checked again.

When $i reaches 6, the loop terminates.

Example 2: Countdown Using a While Loop

<?php
$count = 5;

while ($count >= 1) {
    echo $count . "<br>";
    $count--;
}

echo "Finished!";
?>

Output:

5
4
3
2
1
Finished!

The decrement operator $count-- reduces the value by one during each iteration.

Important: Always make sure the condition can eventually become false. Otherwise, you may create an infinite loop.

5. Do-While Loop in PHP

The do-while loop is similar to the while loop, but there is one important difference: it executes the code block at least once, even if the condition is false initially.

Syntax

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

Notice the semicolon after the while condition.

Example 1: Print Numbers from 1 to 5

<?php
$i = 1;

do {
    echo $i . "<br>";
    $i++;
} while ($i <= 5);
?>

Output:

1
2
3
4
5

Example 2: Condition Is False Initially

<?php
$i = 10;

do {
    echo "Value: " . $i;
} while ($i < 5);
?>

Output:

Value: 10

Although $i < 5 is false, the message is printed once because the code block runs before the condition is checked.

6. Foreach Loop in PHP

The foreach loop is designed to work with arrays. It allows you to access each element without manually managing an index.

It is especially useful when displaying lists of products, users, categories, or other records.

Syntax for Indexed Arrays

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

Example 1: Display an Array of Fruits

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

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

Output:

Apple
Banana
Mango
Orange

PHP assigns each array element to $fruit during each iteration.

Example 2: Display Array Keys and Values

<?php
$colors = ["red", "green", "blue"];

foreach ($colors as $key => $color) {
    echo $key . " : " . $color . "<br>";
}
?>

Output:

0 : red
1 : green
2 : blue

Here, $key stores the array index and $color stores the corresponding value.

Example 3: Foreach with an Associative Array

An associative array uses named keys instead of numeric indexes.

<?php
$student = [
    "name" => "Rahul",
    "age" => 21,
    "course" => "PHP"
];

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

Output:

name : Rahul
age : 21
course : PHP

This approach is useful when displaying information stored as key-value pairs.

7. Difference Between For, While, Do-While, and Foreach

Loop Best Use Condition Checked
for Repeating a known number of times Before each iteration
while Repeating while a condition is true Before each iteration
do-while Ensuring the code runs at least once After each iteration
foreach Iterating through arrays Automatically for each element

Beginner tip: Use for for counting, while for condition-based repetition, do-while when the code must execute at least once, and foreach for arrays.

8. Break Statement in PHP

The break statement immediately terminates the current loop.

Example: Stop the Loop at Number 3

<?php
for ($i = 1; $i <= 5; $i++) {
    if ($i == 4) {
        break;
    }

    echo $i . "<br>";
}
?>

Output:

1
2
3

When $i becomes 4, break stops the loop completely.

Real-World Use

Suppose you are searching a list of products and want to stop once you find the product you need. A break statement can prevent unnecessary iterations.

9. Continue Statement in PHP

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

Example: Skip Number 3

<?php
for ($i = 1; $i <= 5; $i++) {
    if ($i == 3) {
        continue;
    }

    echo $i . "<br>";
}
?>

Output:

1
2
4
5

When $i is 3, PHP skips the echo statement for that iteration. The loop continues with the next number.

Difference Between Break and Continue

  • break ends the loop entirely.

  • continue skips the current iteration but keeps the loop running.

10. Nested Loops in PHP

A nested loop is a loop placed inside another loop. Nested loops are useful for working with tables, grids, and combinations of values.

Example: Print a Simple Number Pattern

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

    echo "<br>";
}
?>

Output:

1 2 3
1 2 3
1 2 3

The outer loop controls the rows, while the inner loop prints the numbers in each row.

11. Real-World Example: Display Products Using a Loop

Imagine an online store that needs to display a list of products.

<?php
$products = [
    "Laptop",
    "Mobile Phone",
    "Keyboard",
    "Mouse"
];

echo "<h2>Product List</h2>";

foreach ($products as $product) {
    echo "<p>" . htmlspecialchars($product, ENT_QUOTES, 'UTF-8') . "</p>";
}
?>

Output in the browser:

Product List

Laptop

Mobile Phone

Keyboard

Mouse

The foreach loop displays each product automatically. The htmlspecialchars() function helps prevent product text containing HTML special characters from being interpreted as markup.

This approach can be adapted to product lists, category lists, and other data-driven pages.

12. Common Mistakes When Using Loops in PHP

Mistake 1: Forgetting to Increment the Variable

Incorrect:

<?php
$i = 1;

while ($i <= 5) {
    echo $i;
}
?>

This creates an infinite loop because $i never changes.

Correct:

<?php
$i = 1;

while ($i <= 5) {
    echo $i . "<br>";
    $i++;
}
?>

Mistake 2: Using the Wrong Loop Condition

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

This prints 1 through 4, not 1 through 5.

To include 5, use $i <= 5.

Mistake 3: Forgetting the Semicolon in Do-While

Incorrect:

do {
    echo "Hello";
} while (false)

Correct:

do {
    echo "Hello";
} while (false);

Mistake 4: Using Foreach on a Non-Array

Make sure the variable contains an iterable value before using foreach. Passing an unsuitable value can generate warnings or errors, depending on the value and PHP version.

Mistake 5: Creating an Infinite Loop Accidentally

Always check whether your loop has a valid stopping condition and whether the variables involved are updated correctly.

13. Practice Exercises for Beginners

Try solving these exercises yourself before checking a solution.

Exercise 1: Print numbers from 1 to 10 using a for loop.

Exercise 2: Print all even numbers between 1 and 20.

Exercise 3: Calculate the sum of numbers from 1 to 100.

Exercise 4: Use a while loop to print numbers from 10 down to 1.

Exercise 5: Create an array of five city names and display them using foreach.

Exercise 6: Print numbers from 1 to 10 but skip number 5 using continue.

Exercise 7: Print numbers from 1 to 10 and stop the loop when the number reaches 7 using break.

Exercise 8: Create an associative array containing a student's name, age, and course. Display its keys and values using foreach.

Sample Solution: Sum from 1 to 100

<?php
$sum = 0;

for ($i = 1; $i <= 100; $i++) {
    $sum += $i;
}

echo "Sum = " . $sum;
?>

Output:

Sum = 5050

14. Frequently Asked Questions (FAQs)

1. What is a loop in PHP?

A loop is a control structure that repeats a block of code while a condition is satisfied or while elements remain to be processed.

2. How many types of loops are available in PHP?

PHP has four commonly used loop structures: for, while, do-while, and foreach.

3. What is the difference between for and while loops?

A for loop is often used when the number of iterations is known. A while loop is often used when repetition depends on a condition.

4. Which PHP loop executes at least once?

The do-while loop executes its body at least once because it checks the condition after executing the body.

5. Why is foreach used in PHP?

The foreach loop makes it easy to iterate through arrays and access their values, and optionally their keys, without manually managing an index.

6. What is the difference between break and continue?

break terminates the loop, while continue skips the current iteration and proceeds to the next one.

7. Can loops be nested in PHP?

Yes. You can place one loop inside another to process tables, grids, patterns, and multidimensional arrays.

Conclusion

Loops are an essential part of Core PHP because they allow you to execute repetitive tasks without writing the same code multiple times.

In this module, you learned how to use for, while, do-while, and foreach loops, along with break, continue, and nested loops.

Practice these examples and exercises to strengthen your understanding. Loops will become especially useful when you start working with arrays, database records, and dynamic website content.