🎢 PHP Loops: The Magical Merry-Go-Round of Code
Imagine you have a box of 100 toy cars. Would you pick them up one by one, saying “I pick up car 1… I pick up car 2…”? That would take forever! Loops are like magic spells that do boring, repetitive work for you!
🎯 What Are Loops?
Think of a loop like a merry-go-round at the playground. It goes round and round until someone says “STOP!”
In PHP, loops let your computer do the same thing many times without you writing the same code over and over.
Without a loop:
echo "Hello!";
echo "Hello!";
echo "Hello!";
echo "Hello!";
echo "Hello!";
// Ugh... 95 more times? No way!
With a loop:
for ($i = 0; $i < 100; $i++) {
echo "Hello!";
}
// Done! 100 hellos in 3 lines!
🔄 The while Loop
The Story
Imagine you’re eating cookies. You keep eating while there are cookies left in the jar.
graph TD A[Start] --> B{Cookies left?} B -->|Yes| C[Eat one cookie] C --> B B -->|No| D[Stop eating]
How It Works
The while loop checks a condition FIRST, then does the work.
$cookies = 5;
while ($cookies > 0) {
echo "Yum! Eating cookie!<br>";
$cookies--;
}
echo "No more cookies!";
Output:
Yum! Eating cookie!
Yum! Eating cookie!
Yum! Eating cookie!
Yum! Eating cookie!
Yum! Eating cookie!
No more cookies!
⚠️ Watch Out!
If you forget to change the condition, your loop runs FOREVER! This is called an infinite loop.
// DANGER! Never do this!
$cookies = 5;
while ($cookies > 0) {
echo "Eating..."; // Oops! Forgot to eat!
// $cookies-- is missing!
}
🔁 The do-while Loop
The Story
This is like a “taste test” loop. You ALWAYS try the food at least once, THEN decide if you want more.
The Key Difference
while: Checks first, then actsdo-while: Acts first, then checks
$bravery = 0;
do {
echo "I'll try this scary ride!<br>";
$bravery++;
} while ($bravery < 3);
Output:
I'll try this scary ride!
I'll try this scary ride!
I'll try this scary ride!
Real Example: Ask Until Correct
$password = "";
do {
$password = readline("Enter password: ");
} while ($password != "secret123");
echo "Welcome in!";
Even if the user types wrong, they get asked AT LEAST ONCE!
🎯 The for Loop
The Story
The for loop is like a coach counting push-ups: “1… 2… 3… done!”
It’s perfect when you KNOW how many times you want to repeat.
The Three Magic Parts
for (start; condition; step) {
// do stuff
}
| Part | What It Does | Example |
|---|---|---|
| Start | Where to begin | $i = 1 |
| Condition | When to stop | $i <= 10 |
| Step | How to move | $i++ |
Simple Example
for ($i = 1; $i <= 5; $i++) {
echo "Counting: $i<br>";
}
Output:
Counting: 1
Counting: 2
Counting: 3
Counting: 4
Counting: 5
Countdown Example
for ($rocket = 10; $rocket >= 1; $rocket--) {
echo "$rocket...<br>";
}
echo "🚀 BLAST OFF!";
⏸️ The break Statement
The Story
break is like the EMERGENCY STOP button on the merry-go-round. It instantly stops the loop!
for ($i = 1; $i <= 100; $i++) {
echo "Looking at toy #$i<br>";
if ($i == 3) {
echo "Found my favorite toy!";
break; // STOP! No need to look further
}
}
Output:
Looking at toy #1
Looking at toy #2
Looking at toy #3
Found my favorite toy!
We never reached toys #4 to #100. break stopped us early!
⏭️ The continue Statement
The Story
continue is like saying “Skip this one, next please!” It skips the rest of the current round but KEEPS the loop going.
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
echo "Skipping #3!<br>";
continue; // Jump to next round
}
echo "Processing #$i<br>";
}
Output:
Processing #1
Processing #2
Skipping #3!
Processing #4
Processing #5
Real Example: Skip Even Numbers
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue; // Skip even numbers
}
echo "$i "; // Only prints odd!
}
// Output: 1 3 5 7 9
🎒 The foreach Loop
The Story
foreach is like a tour guide for arrays. It visits EVERY item, one by one, without you counting!
Basic Syntax
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo "I love $fruit!<br>";
}
Output:
I love Apple!
I love Banana!
I love Cherry!
With Keys (Index Numbers)
$colors = ["Red", "Green", "Blue"];
foreach ($colors as $index => $color) {
echo "Color #$index is $color<br>";
}
Output:
Color #0 is Red
Color #1 is Green
Color #2 is Blue
With Associative Arrays
$ages = [
"Tom" => 10,
"Sara" => 8,
"Max" => 12
];
foreach ($ages as $name => $age) {
echo "$name is $age years old<br>";
}
Output:
Tom is 10 years old
Sara is 8 years old
Max is 12 years old
📝 Alternative Syntax
The Story
PHP has a cleaner look for loops when you’re mixing HTML and PHP. It uses colons (:) and special ending words.
Standard vs Alternative
Standard (uses curly braces):
<?php foreach ($items as $item) { ?>
<li><?php echo $item; ?></li>
<?php } ?>
Alternative (uses colon + endforeach):
<?php foreach ($items as $item): ?>
<li><?php echo $item; ?></li>
<?php endforeach; ?>
All Loop Alternatives
| Standard | Alternative Start | Alternative End |
|---|---|---|
while () { } |
while (): |
endwhile; |
for () { } |
for (): |
endfor; |
foreach () { } |
foreach (): |
endforeach; |
Real HTML Example
<?php $students = ["Amy", "Bob", "Cat"]; ?>
<ul>
<?php foreach ($students as $student): ?>
<li><?= $student ?></li>
<?php endforeach; ?>
</ul>
Produces:
<ul>
<li>Amy</li>
<li>Bob</li>
<li>Cat</li>
</ul>
🧠 Quick Comparison
| Loop Type | Best For | Checks First? |
|---|---|---|
while |
Unknown repetitions | ✅ Yes |
do-while |
At least once needed | ❌ No |
for |
Known count | ✅ Yes |
foreach |
Arrays | ✅ Yes |
graph TD A[Need a Loop?] --> B{Know how many times?} B -->|Yes| C[Use FOR] B -->|No| D{Have an array?} D -->|Yes| E[Use FOREACH] D -->|No| F{Must run at least once?} F -->|Yes| G[Use DO-WHILE] F -->|No| H[Use WHILE]
🎉 You Did It!
You just learned the 5 types of loops in PHP:
- while - Keep going while something is true
- do-while - Do it once, then check
- for - Count from start to end
- foreach - Visit every item in an array
- Alternative syntax - Cleaner look in HTML
Plus the 2 control keywords:
- break - Emergency stop!
- continue - Skip this one, next!
Now your code can repeat things automatically, like a tireless robot friend! 🤖