Loops in PHP help execute code repeatedly and are essential for handling tasks like data fetching, pagination, and array processing. Use while for unknown iterations, for for fixed counts, foreach for arrays, and do...while when the block must run at least once.

When building dynamic applications in PHP—whether it's a blog, admin dashboard, eCommerce platform, or API—loops become an essential part of your coding toolkit. They help you perform repetitive tasks efficiently, like rendering lists, processing arrays, and handling user input.
In this post, we’ll explore all types of loops in PHP with real-world use cases, not just simple number counting. We’ll also cover how to decide which loop is best for each situation.
What Is a Loop in PHP?
A loop allows you to run a block of code repeatedly under certain conditions. It's a time-saver and helps write cleaner, more manageable code.
Types of Loops in PHP
while
do...while
for
foreach
break
&continue
(loop control)
1. while
Loop
Real-World Example: Fetching Users from Database
$conn = new mysqli("localhost", "root", "", "mydb");
$result = $conn->query("SELECT * FROM users");
while ($user = $result->fetch_assoc()) {
echo "Name: {$user['name']} - Email: {$user['email']}<br>";
}
Use When:
You don't know how many iterations you need, like reading from a database or external API.
2. do...while
Loop
Real-World Example: Retrying a Payment
$attempt = 0;
$success = false;
do {
$success = tryPayment(); // simulate payment logic
$attempt++;
} while (!$success && $attempt < 3);
echo $success ? "Payment Successful" : "Failed after 3 attempts.";
Use When:
The block must run at least once (e.g., user input, retry logic).
3. for
Loop
Real-World Example: Generate Pagination
$totalPages = 10;
for ($i = 1; $i <= $totalPages; $i++) {
echo "<a href='?page=$i'>Page $i</a> ";
}
Use When:
The number of iterations is known in advance—ideal for:
- Generating page numbers
- Running tasks in a loop
4. foreach
Loop
Real-World Example: Display Products
$products = [
["name" => "iPhone 15", "price" => 799],
["name" => "Samsung S24", "price" => 699],
["name" => "OnePlus 12", "price" => 649],
];
foreach ($products as $product) {
echo "<div class='card'>";
echo "<h2>{$product['name']}</h2>";
echo "<p>Price: $ {$product['price']}</p>";
echo "</div>";
}
Use When:
Working with arrays or objects from:
- API responses
- Form data
- Settings/config files
5. break
and continue
break
– Exit the loop immediately
Use Case: Stop at First Match
$emails = ["a@example.com", "b@example.com", "admin@example.com"];
$search = "admin@example.com";
foreach ($emails as $email) {
if ($email === $search) {
echo "Admin email found!";
break;
}
}
continue
– Skip current iteration
Use Case: Ignore Inactive Users
$users = [
["name" => "Dinesh", "active" => true],
["name" => "Ashish", "active" => false],
["name" => "Kiran", "active" => true],
];
foreach ($users as $user) {
if (!$user['active']) continue;
echo "{$user['name']} is active.<br>";
}
When to Use Which Loop?
Scenario | Recommended Loop | Why? |
---|---|---|
Reading database records | while | Unknown count of rows |
Retry logic or guaranteed 1 run | do...while | Needs at least one execution |
Known range (1 to 10, etc.) | for | Clean structure for fixed iterations |
Working with array data | foreach | Clean, readable syntax |
Stop loop early | break | Exit based on condition |
Skip specific iteration | continue | Avoid processing certain items |
Bonus Real-World Use Case: Notifications Panel
$notifications = [
["title" => "New user registered", "read" => false],
["title" => "Order #123 completed", "read" => true],
["title" => "New comment", "read" => false],
];
foreach ($notifications as $note) {
if ($note['read']) {
echo "<p>{$note['title']}</p>";
} else {
echo "<p><strong>[New]</strong> {$note['title']}</p>";
}
}
This type of foreach
logic is perfect for dashboards, admin panels, or inbox systems.
Final Thoughts
Understanding how and when to use each loop makes your code cleaner, more efficient, and easier to maintain.
while
is perfect for uncertain lengths (like DB reads).do...while
is ideal when something must run at least once.for
is great for known ranges or indexes.foreach
is your best friend for arrays.- Use
break
andcontinue
for more control within any loop.
Whether you’re building a CRM, API, blog CMS, or ecommerce platform, mastering these loops will help you write better PHP.
Happy Coding! 😊