PHP CHAPTER 18

PHP Loops

Loops repeat a block of code.

📘

What is it?

Loops repeat a block of code.

💡

Why do we use it?

Loops avoid writing the same code repeatedly.

⚙️

How does it work?

A loop checks a condition or iterates through a collection and executes its body repeatedly.

🧩

Syntax

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

Example

PHP Example
<?php

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

?>
🔍

Example Explained

The loop starts at 1, checks whether i is less than or equal to 5, prints it and increments it.
🚀

More Examples

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

⚠️ Important Rules

PHP supports for, while, do-while and foreach loops.

❌ Common Mistakes

Creating an infinite loop by forgetting to change the loop variable.

🌍 Real-World Use

Displaying database rows, processing arrays and generating reports.

📝 Practice Exercise

Print the multiplication table of 7 using a loop.

💻 Try It Yourself

Write and run this PHP lesson inside the AIFA Coding Lab.

Open Coding Lab →