What Are We Doing in This Post?
In Episode 05, PHP learned how to make decisions. Now we teach it to repeat tasks.
Imagine you have 100 products to display on a page. You are not going to write echo 100 times. You write the logic once, tell PHP how many times to repeat it, and PHP handles the rest. That is what loops do.
Loops are one of the most powerful and most used concepts in all of programming. Master this episode and a huge chunk of real-world PHP will start making sense immediately.
The while Loop — Repeat As Long As Something is True
Real world analogy: You are filling a bucket with water. You keep pouring as long as the bucket is not full. The moment it is full, you stop. That is a while loop.
<?php
$count = 1;
while ($count <= 5) { echo "Count is: $count"; echo "<br>"; $count++; }
?>
Output:
Count is: 1 Count is: 2 Count is: 3 Count is: 4 Count is: 5
PHP checks the condition before every iteration. Is $count less than or equal to 5? If yes, run the block. After each run, $count increases by 1. When $count reaches 6, the condition becomes false and the loop stops.
The $count++ line is critical. Without it, $count never changes, the condition is always true, and the loop runs forever. This is called an infinite loop and it will crash your server. Always make sure your loop has a way to eventually become false.
The do while Loop — Run First, Check Later
The do while loop is similar to while, but with one key difference: it runs the code block first and checks the condition after. This guarantees the block runs at least once, even if the condition is false from the start.
<?php
$number = 10;
do { echo "Number is: $number"; echo "<br>"; $number++; } while ($number < 5);
?>
Output:
Number is: 10
Even though $number is already 10 and the condition $number < 5 is immediately false, the block still runs once because the check happens after the first execution.
Real world use: showing a user a form at least once, and then re-showing it only if validation fails.
The for Loop — When You Know Exactly How Many Times
The for loop is the most precise loop. You use it when you know in advance exactly how many times you want to repeat something.
<?php
for ($i = 1; $i <= 5; $i++) { echo "Iteration: $i"; echo "<br>"; }
?>
Output:
Iteration: 1 Iteration: 2 Iteration: 3 Iteration: 4 Iteration: 5
The for loop has three parts inside the parentheses, separated by semicolons.
The first part is the initializer: $i = 1. This runs once at the very beginning and sets up the counter variable.
The second part is the condition: $i <= 5. PHP checks this before every iteration. If true, the block runs. If false, the loop stops.
The third part is the increment: $i++. This runs after every iteration, updating the counter.
All three parts in one line makes for loops very readable. When you see a for loop, you immediately know the start, the end, and the step.
Counting Backwards and Custom Steps
The for loop is flexible. You can count in any direction and any step size.
<?php
for ($i = 10; $i >= 1; $i--) { echo "$i "; }
?>
Output: 10 9 8 7 6 5 4 3 2 1
<?php
for ($i = 0; $i <= 20; $i += 5) { echo "$i "; }
?>
Output: 0 5 10 15 20
The second example increments by 5 each time using $i += 5. You can step by any amount you need.
The foreach Loop — Made for Arrays
The foreach loop is designed specifically to loop through arrays. Arrays are lists of values — we will cover them in full detail in Episode 07. But for now, think of an array as a list.
<?php
$fruits = ["Apple", "Banana", "Mango", "Orange", "Grapes"];
foreach ($fruits as $fruit) { echo $fruit; echo "<br>"; }
?>
Output:
Apple Banana Mango Orange Grapes
foreach goes through the array one item at a time. On each iteration, the current item is stored in $fruit and you can use it inside the block. PHP automatically knows when the list ends and stops.
You do not manage a counter yourself. You do not worry about going out of bounds. foreach handles all of that. This is the loop you will use most often in real Laravel applications.
foreach With Key and Value
Arrays in PHP have both keys and values. foreach can give you both at the same time.
<?php
$person = [ "name" => "Gagan", "age" => 22, "city" => "Delhi", "job" => "Developer" ];
foreach ($person as $key => $value) { echo "$key: $value"; echo "<br>"; }
?>
Output:
name: Gagan age: 22 city: Delhi job: Developer
The => symbol maps a key to a value. This is called an associative array and we will go deep into arrays in Episode 07. For now just notice how foreach with $key => $value gives you both pieces of information on every iteration.
break and continue — Controlling Loop Flow
Sometimes you need to exit a loop early or skip a specific iteration. PHP gives you two keywords for this.
break — exit the loop immediately:
<?php
for ($i = 1; $i <= 10; $i++) { if ($i == 6) { break; } echo "$i "; }
?>
Output: 1 2 3 4 5
When $i reaches 6, break exits the loop completely. Numbers 6 through 10 are never printed.
Real world use: searching through a list for a specific item. Once you find it, you break out of the loop — no point checking the rest.
continue — skip this iteration and move to the next:
<?php
for ($i = 1; $i <= 10; $i++) { if ($i % 2 == 0) { continue; } echo "$i "; }
?>
Output: 1 3 5 7 9
When $i is even (divisible by 2 with no remainder), continue skips the echo and jumps straight to the next iteration. Only odd numbers get printed.
Real world use: processing a list but skipping items that do not meet certain criteria — for example, skipping inactive users when sending a newsletter.
Nested Loops — Loops Inside Loops
You can put a loop inside another loop. The inner loop completes fully for every single iteration of the outer loop.
<?php
for ($row = 1; $row <= 3; $row++) { for ($col = 1; $col <= 3; $col++) { echo "[$row,$col] "; } echo "<br>"; }
?>
Output:
[1,1] [1,2] [1,3] [2,1] [2,2] [2,3] [3,1] [3,2] [3,3]
For each value of $row, the inner loop runs completely through all three values of $col. Real world use: generating a calendar grid, building a multiplication table, or rendering rows and columns of data in a table.
A Real World Example — Product Listing Page
Let us build something practical. A simple product listing page that a real e-commerce site might generate.
Create a new file called products.php in your phplearning folder:
<!DOCTYPE html> <html> <head> <title>Product Listing</title> </head> <body>
<h2>Our Products</h2>
<?php
$products = [ ["name" => "Wireless Mouse", "price" => 599, "stock" => 15], ["name" => "Mechanical Keyboard", "price" => 2499, "stock" => 0], ["name" => "USB Hub", "price" => 899, "stock" => 8], ["name" => "Webcam HD", "price" => 1799, "stock" => 0], ["name" => "Monitor Stand", "price" => 1199, "stock" => 22], ];
foreach ($products as $product) { echo "<div style='border: 1px solid #ccc; padding: 10px; margin: 10px 0;'>"; echo "<h3>" . $product["name"] . "</h3>"; echo "<p>Price: Rs. " . $product["price"] . "</p>";
if ($product["stock"] > 0) {
echo "<p style='color: green;'>In Stock (" . $product["stock"] . " units)</p>";
echo "<button>Add to Cart</button>";
} else {
echo "<p style='color: red;'>Out of Stock</p>";
}
echo "</div>";
}
?>
</body> </html>
Visit http://localhost:8080/phplearning/products.php
You will see five product cards. Two of them show Out of Stock in red with no Add to Cart button. Three show In Stock in green with the button. This is exactly how real product listing pages work — one loop, one set of logic, handling every product dynamically.
Notice how loops and conditionals work together here. The foreach handles repetition. The if/else inside handles the per-product logic. These two concepts combined are the backbone of almost every dynamic web page you will ever build.
Choosing the Right Loop
Here is a simple guide for deciding which loop to use.
Use while when you do not know in advance how many times you need to loop — you just know the stopping condition.
Use do while when you need the block to run at least once before checking the condition.
Use for when you know the exact number of iterations upfront.
Use foreach when you are working with an array or a list of items. This will be your most used loop in Laravel.
What Did We Learn in This Post?
while loops repeat as long as a condition is true. Always ensure the condition can eventually become false.
do while loops run the block first and check the condition after — guaranteed at least one execution.
for loops are precise — initializer, condition, and increment all defined in one line. Best when you know the exact count.
foreach loops are built for arrays — they handle the iteration automatically without manual counter management.
break exits a loop immediately. continue skips the current iteration and moves to the next.
Nested loops let you work with grid-like data — a complete inner loop runs for every single outer iteration.
What is Coming in Episode 07?
We used arrays briefly in this episode. In Episode 07 we go deep into them.
Arrays are how PHP stores and manages lists and collections of data. Indexed arrays, associative arrays, multidimensional arrays, and all the built-in array functions PHP provides. This is one of the most important episodes in the entire Core PHP section.
See you in the next one.
Next Episode: Arrays — Storing and Managing Collections of Data in PHP
This is Episode 06 of the PHP and Laravel — Zero to Hero series.
No comments:
Post a Comment