PHP Loops


In programming, you often need to repeat certain tasks — like displaying a list of students, calculating totals, or processing records from a database. Writing the same code multiple times isn’t efficient. That’s where loops come in.

A loop allows you to run a block of code multiple times automatically, until a specific condition is met. In PHP, loops are essential for handling repetitive tasks quickly and neatly.

Why Use Loops in PHP?

Imagine you want to print numbers from 1 to 100. Without loops, you’d have to write 100 echo statements — clearly not practical.

With loops, you can do it with just a few lines of code:

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

That’s the power of loops — automating repetition efficiently.

Types of Loops in PHP

PHP provides four main types of loops, each suited for a specific use case:

  1. while loop – Repeats as long as a condition is true.

  2. do...while loop – Runs the code once before checking the condition.

  3. for loop – Used when you know how many times to run the loop.

  4. foreach loop – Special loop used for arrays.

Let’s go through each in detail.

PHP While Loop

The while loop executes a block of code as long as the given condition is true.

Syntax:

while (condition) {
    // Code to be executed
}

Example:

<?php
$count = 1;

while ($count <= 5) {
    echo "Count is: $count <br>";
    $count++;
}
?>

Explanation:

  • PHP checks the condition $count <= 5.

  • If it’s true, the code block runs.

  • The variable $count increases by 1 each time.

  • When $count becomes 6, the loop stops.

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5

Use a while loop when you don’t know exactly how many times the code should run (for example, reading data until the end of a file).

PHP Do...While Loop

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

Syntax:

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

Example:

<?php
$number = 1;

do {
    echo "Number: $number <br>";
    $number++;
} while ($number <= 5);
?>

Difference:
In do...while, the code runs first, then the condition is checked.

So even if $number started greater than 5, it would still print once.

PHP For Loop

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

Syntax:

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

Example:

<?php
for ($i = 1; $i <= 10; $i++) {
    echo "The number is: $i <br>";
}
?>

Explanation:

  1. $i = 1 → The loop starts with 1.

  2. $i <= 10 → The loop continues as long as this condition is true.

  3. $i++ → After each iteration, $i increases by 1.

Output:

The number is: 1
The number is: 2
...
The number is: 10

This loop is best for counting, printing sequences, and handling known ranges of data.

PHP Foreach Loop

The foreach loop is specifically designed for arrays. It lets you loop through each item in an array without worrying about indexes.

Syntax:

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

Or, if you want both key and value:

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

Example:

<?php
$students = ["Vicky", "Sanjana", "Vrinda", "Riya"];

foreach ($students as $name) {
    echo "Student: $name <br>";
}
?>

Output:

Student: Vicky
Student: Sanjana
Student: Vrinda
Student: Riya

Example with keys:

<?php
$marks = [
    "Vicky" => 90,
    "Sanjana" => 85,
    "Vrinda" => 78
];

foreach ($marks as $student => $score) {
    echo "$student scored $score marks. <br>";
}
?>

The foreach loop is heavily used when working with arrays, JSON data, or database results.

Nested Loops in PHP

You can use a loop inside another loop — this is called a nested loop.
Useful for working with multi-dimensional arrays or tables.

Example:

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

Output:

(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)

Nested loops are commonly used for grids, tables, and structured data like seating plans or calendars.

Controlling Loops with Break and Continue

Sometimes you need to stop a loop early or skip certain iterations. PHP gives you two control keywords for this: break and continue.

Break Example:

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

Output:

1 2 3 4

Here, the loop stops completely when $i becomes 5.

Continue Example:

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

Output:

1 2 4 5

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

Infinite Loops

If the condition in a loop never becomes false, the loop runs forever — that’s called an infinite loop.
Be careful with these as they can crash your program.

Example:

<?php
while (true) {
    echo "This will run forever!";
}
?>

Always make sure your loop has a clear exit condition.

Real-Life Example: Calculating Total Marks

Let’s use a loop in a simple practical example.

<?php
$marks = [80, 75, 92, 68, 88];
$total = 0;

foreach ($marks as $score) {
    $total += $score;
}

$average = $total / count($marks);
echo "Total Marks: $total <br>";
echo "Average Marks: $average";
?>

Output:

Total Marks: 403
Average Marks: 80.6

This kind of logic is common in student report systems, sales summaries, and data analytics.

Common Mistakes in Loops

  1. Forgetting to update the loop variable
    Causes infinite loops.

  2. Using wrong conditions
    (<= instead of < or vice versa) can skip or overcount iterations.

  3. Modifying an array while looping
    Avoid changing array structure during a foreach.

  4. Heavy operations inside loops
    Move calculations outside the loop for better performance.

Best Practices

  • Always make sure your loop condition ends logically.

  • Use for when you know the exact count.

  • Use while when the end depends on data or user input.

  • Prefer foreach for arrays — it’s clean and safe.

  • Keep loops efficient; avoid unnecessary work inside them.

Summary of the Tutorial

  • Loops are used to execute repetitive code automatically.

  • PHP has four main loops: while, do...while, for, and foreach.

  • Use break to stop a loop and continue to skip one iteration.

  • Be careful of infinite loops by managing conditions properly.

  • Loops make your PHP programs more efficient, organized, and scalable.

By mastering loops, you’ll handle repetitive tasks in your PHP projects with ease — whether it’s displaying records, calculating totals, or processing data dynamically.


Practice Questions

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

  2. Create a PHP script using a while loop to print all even numbers between 1 and 20.

  3. Write a PHP program using a do...while loop to display numbers from 10 down to 1.

  4. Create a PHP foreach loop to print all names from an array of student names.

  5. Write a PHP program using nested for loops to display a 5x5 multiplication table.

  6. Create a PHP script using break to stop a loop when a number divisible by 7 is found between 1 and 20.

  7. Write a PHP program using continue to skip printing numbers divisible by 3 between 1 and 15.

  8. Create a PHP for loop that prints only odd numbers between 1 and 25.

  9. Write a PHP program to calculate the sum of all elements in an array using a foreach loop.

  10. Create a PHP program using nested loops to print a right-angled triangle pattern of asterisks with 5 rows.


Go Back Top