🔁 PHP Control Flow & Logic
Estimated reading: 3 minutes 46 views

🔁 PHP Loop Types – for, foreach, while, do…while Explained

A complete guide to while, do...while, for, and foreach loops in PHP with examples, syntax, and best practices.


🧲 Introduction – Why Loops Matter in PHP

Loops are essential for executing a block of code multiple times. Whether you’re displaying a list of records, generating repetitive HTML, or calculating values — PHP’s loop structures help automate repetitive tasks efficiently.

🎯 In this guide, you’ll learn:

  • The 4 primary loop types in PHP
  • Syntax and use cases for each loop
  • How to control loop execution with break and continue
  • Loop performance tips and clean coding practices

🔄 1. while Loop

Repeats as long as the condition is true.

$i = 1;

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

🔍 Output:

Count: 1
Count: 2
Count: 3

📘 Use Case: Unknown number of iterations; condition-based execution.


🔁 2. do...while Loop

Executes the block at least once, even if the condition is false.

$j = 1;

do {
    echo "Step: $j <br>";
    $j++;
} while ($j <= 3);

🔍 Output:

Step: 1
Step: 2
Step: 3

📘 Use Case: When at least one execution is guaranteed, like input validation.


🔃 3. for Loop

Best for a known number of iterations.

for ($k = 0; $k < 3; $k++) {
    echo "Loop: $k <br>";
}

🔍 Output:

Loop: 0
Loop: 1
Loop: 2

📘 Use Case: Fixed iteration counts, numeric counters, indexed arrays.


🔄 4. foreach Loop

Specifically designed to iterate over arrays and objects.

$colors = ['red', 'green', 'blue'];

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

🔍 Output:

Color: red
Color: green
Color: blue

📘 Use Case: Array iteration. Cleanest loop for key/value pairs.


🧭 foreach with Keys

$person = ['name' => 'John', 'age' => 30];

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

🔍 Output:

name: John
age: 30

⛓️ Loop Control: break and continue

🚫 break – Exit the loop entirely

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

🔍 Output: 1 2


🔂 continue – Skip current iteration

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

🔍 Output: 1 2 4 5


🔬 Loop Selection Summary

Loop TypeWhen to Use
whileLoop until condition is false
do...whileAlways run at least once
forKnown number of steps
foreachBest for arrays and collections

🧠 Best Practices

  • ✅ Use foreach for arrays — it’s faster and cleaner
  • ✅ Initialize variables outside the loop
  • ✅ Use break for exiting early
  • ✅ Minimize logic inside loops for performance
  • ❌ Avoid modifying the array you’re looping over (foreach may behave unpredictably)

📌 Summary – Recap & Next Steps

Loops help automate repetitive tasks in your PHP scripts, from listing users to validating forms. Mastering each loop type makes your code more efficient and clean.

🔍 Key Takeaways:

  • while — Runs while condition is true
  • do...while — Runs at least once
  • for — Best for numeric or counted loops
  • foreach — Ideal for arrays and objects

⚙️ Real-World Use Cases:
Used in shopping carts, pagination, report generation, and dynamic UI rendering.


❓ Frequently Asked Questions (FAQs)

❓ Which loop is best for arrays in PHP?
foreach — It’s designed for array traversal and avoids indexing errors.

❓ When should I use do...while?
✅ When the loop must run at least once, like reading user input.

❓ Can I use break inside foreach?
✅ Yes — break exits any type of loop.

❓ What’s the difference between continue and break?
continue skips current iteration; break exits the loop entirely.

❓ Is foreach faster than for?
✅ Generally yes, especially for associative arrays.


Share Now :

Leave a Reply

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

Share

🔁 PHP — Loop Types

Or Copy Link

CONTENTS
Scroll to Top