PHP Loops Explained (for, while, foreach) with Examples

Introduction

PHP loops are used to execute a block of code multiple times. In this guide, you’ll learn how to use for, while, do…while, and foreach loops in PHP with simple examples.

Loops are widely used in real projects—especially in dynamic websites and platforms like WordPress—to display data such as posts, users, and comments efficiently.

🎯 What You’ll Learn

  • What PHP loops are and why they are used
  • How to use for, while, do…while, and foreach loops
  • When to use each type of loop
  • Real-life examples of PHP loops
  • Common mistakes to avoid

Why Use Loops?

Imagine you want to print numbers from 1 to 10.

Without loops, you would need to write echo statements multiple times.

Example without a loop:

<?php
echo 1;
echo 2;
echo 3;
echo 4;
echo 5;
?>

This approach quickly becomes inefficient and difficult to maintain.

Loops solve this problem by allowing you to repeat code automatically.

Using loops helps you:

  • Save time
  • Reduce code duplication
  • Write cleaner and more efficient programs
  • Handle dynamic data easily

Types of Loops in PHP

PHP supports the following types of loops:

  1. for loop
  2. while loop
  3. do...while loop
  4. foreach loop

Let’s understand each one with examples.

1. PHP for Loop (With Example)

The for loop is used when you know how many times the loop should run.

Syntax:

for (initialization; condition; increment/decrement) {
    // code to execute
}

Example:

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

Output:

1
2
3
4
5

Explanation:

  • $i = 1 initializes the counter
  • $i <= 5 is the condition
  • $i++ increases the value after each iteration

The loop stops when the condition becomes false.

2. PHP while Loop (With Example)

The while loop runs as long as the condition is true.

Syntax:

while (condition) {
    // code to execute
}

Example:

$count = 1;

while ($count <= 3) {
    echo "Count: " . $count . "<br>";
    $count++;
}

Output:

Count: 1
Count: 2
Count: 3

The loop continues executing until the condition becomes false.

3. PHP do while Loop (With Example)

The do...while loop executes the code at least once, even if the condition is false.

Syntax:

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

Example:

$num = 5;

do {
    echo "Number is: " . $num;
} while ($num < 3);

Output:

Number is: 5

The code runs once before checking the condition.

4. PHP foreach Loop (With Example)

The foreach loop is mainly used to loop through arrays.

Syntax:

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

Example:

$colors = array("Red", "Green", "Blue");

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

Output:

Red
Green
Blue

Example with Key and Value

Sometimes arrays contain key-value pairs.

Example:

$student = array("name" => "Rahul", "age" => 20);

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

Loop Control Statements

Loop control statements help you manage how loops behave.

break

The break statement stops the loop immediately.

Example:

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

Output:

1
2

continue

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

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

Output:

1
2
4
5

The number 3 is skipped.

💡 Real Life Example of PHP Loops

PHP loops are commonly used to display dynamic data such as users, products, and posts.

Example 1: Displaying User Roles

$users = array("Admin", "Editor", "Subscriber");

foreach ($users as $user) {
    echo "User role: " . $user . "<br>";
}

Example 2: Displaying Products

$products = ["Laptop", "Phone", "Tablet"];

foreach ($products as $product) {
    echo "Product: " . $product . "<br>";
}

👉 These examples show how loops automatically handle repetitive data without writing code multiple times.

When to Use Each Loop

Choosing the right loop makes your code easier to understand and maintain.

🔹 for Loop

Best for: Fixed number of iterations
Example Use Case: Printing numbers from 1 to 10

👉 Use a for loop when you already know how many times the loop should run.

🔹 while Loop

Best for: Condition-based execution
Example Use Case: Processing database records

👉 Use a while loop when the number of iterations depends on a condition.

🔹 do…while Loop

Best for: Run at least once
Example Use Case: Showing a message before validation

👉 Use a do...while loop when the code must execute at least once.

🔹 foreach Loop

Best for: Arrays and collections
Example Use Case: Looping through users or products

👉 Use a foreach loop when working with arrays.

WordPress Loop Explained (Real Example for Beginners)

When working with themes or plugins in WordPress, developers often loop through posts stored in the database. This is commonly known as The WordPress Loop.

Basic WordPress Loop Example:

<?php
if ( have_posts() ) :
    while ( have_posts() ) : the_post();
        the_title();
        the_content();
    endwhile;
else :
    echo "No posts found.";
endif;
?>

What’s happening here?

  • have_posts() checks if posts exist
  • while loops through each post
  • the_title() displays the post title
  • the_content() displays the post content

This is a real-world use of the while loop combined with WordPress functions.

Example: Looping Through Posts Using foreach (WordPress)

In WordPress, sometimes you fetch posts as an array and then loop through them using foreach. This is common when working with custom queries or plugins.

<?php
$args = [
    'post_type'      => 'post',
    'posts_per_page' => 3
];

$posts = get_posts($args);

if (!empty($posts)) {
    foreach ($posts as $post) {
        setup_postdata($post);
        echo "<h3>" . get_the_title() . "</h3>";
    }
    wp_reset_postdata();
} else {
    echo "No posts found.";
}
?>

Explanation (beginner-friendly):

  • get_posts() returns an array of posts
  • foreach loops through each post
  • get_the_title() displays the post title
  • wp_reset_postdata() resets global post data after the loop

When to use this pattern:

  • Showing latest posts in a sidebar
  • Displaying featured posts
  • Building custom widgets

Tip: If this feels advanced, that’s okay. Focus on core PHP loops first and revisit this example later.

❌ Common Mistakes in PHP Loops

Beginners often make these mistakes when working with loops:

  • Forgetting to update loop variables (infinite loops)
  • Using incorrect loop conditions
  • Missing semicolon in do…while
  • Using wrong loop type
  • Misusing foreach with non-arrays

Understanding these mistakes helps you write better and safer code.

Practical Tasks

Task 1: Print Numbers Using for Loop

Write a PHP program to print numbers from 1 to 10 using a for loop.

Task 2: Display Even Numbers

Use a loop to print only even numbers between 1 and 20.

Task 3: Loop Through an Array

Create an array of 5 names and display them using a foreach loop.

Task 4: While Loop Practice

Use a while loop to print numbers from 10 to 1.

Conclusion

PHP loops help you execute code efficiently without repetition. In this tutorial, you learned how to use:

  • for loop – for fixed iterations
  • while loop – for condition-based execution
  • do…while loop – to run code at least once
  • foreach loop – for working with arrays

You also explored real-life examples, common mistakes, and practical tasks to strengthen your understanding.

In the next tutorial, we will learn about PHP Functions and how they help organize reusable code.

Related Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *