What is it?
A loop repeats a block of code until a condition is false. PHP has four loop types each suited to a different situation.
Why does it matter?
Loops are fundamental to processing collections of data — iterating database rows, building HTML lists, sending bulk emails, or retrying failed operations.
Understand all four PHP loop types — for, while, do-while, foreach — when to use each.
Real-World Use Cases
- 📋 Rendering product lists - Use foreach to iterate over a database result array and build an HTML table of products.
- 📧 Sending bulk emails - Loop over a list of subscribers and send each one a personalised newsletter.
- 🔄 Retry logic - Use a while loop to retry a failed API call up to 3 times before giving up.
- 🔢 Generating pagination - Use a for loop to render page number buttons from 1 to the total page count.
foreach Loop — Best for Arrays
<!--?php
$fruits = ['Apple','Banana','Mango'];
foreach ($fruits as $fruit) {
echo $fruit . PHP_EOL;
}
// With key =--> value pairs
$student = ['name' => 'Rahul', 'age' => 21];
foreach ($student as $key => $val) {
echo "$key: $val" . PHP_EOL;
}
break and continue
<!--?php
for ($i=1; $i<=10; $i++) {
if ($i===5) break; // exits loop at 4
echo $i.' ';
}
// Output: 1 2 3 4
for ($i=1; $i<=5; $i++) {
if ($i===3) continue; // skips 3
echo $i.' ';
}
// Output: 1 2 4 5
Q: Which loop should I use for a database result set?
Use foreach when iterating over a fetched array. Use while with fetch() for one row at a time from a PDO statement — more memory-efficient for large result sets.
Comments (0)
No comments yet. Be the first!
Leave a Comment