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
for ($i = 1; $i <= 5; $i++) {
echo $i;
}
Example
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . "<br>";
}
?>
Example Explained
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.