Loops (while, for, foreach)
Why Loops Matter
Loops let you repeat a block of code multiple times without writing it out manually for every repetition. Almost every real PHP application relies on loops constantly — displaying a list of products from a database, validating every field in a submitted form, generating table rows, or processing items in an array. Without loops, you'd need a separate line of code for every single item, which quickly becomes unmanageable.
PHP offers several types of loops, each suited to slightly different situations. This lesson covers all of them: while, do-while, for, and foreach.
The while Loop
A while loop repeats a block of code as long as a given condition remains true. PHP checks the condition before each pass through the loop.
php
<?php
$count = 1;
while ($count <= 5) {
echo $count . "\n";
$count++;
}
// Output: 1 2 3 4 5
The loop continues running as long as $count <= 5 evaluates to true. The $count++ line is critical here — without it, $count would never increase, the condition would always remain true, and the loop would run forever. This is known as an infinite loop, one of the most common bugs beginners run into with while.
while loops are best suited for situations where you don't know in advance exactly how many times you'll need to repeat something — for example, reading lines from a file until there are none left, or repeating an action until a certain condition becomes false.
The do-while Loop
A do-while loop is nearly identical to while, with one key difference: it runs the code block first, and only checks the condition afterward. This guarantees the loop body executes at least once, even if the condition is false from the start.
php
<?php
$attempts = 10;
do {
echo "This runs at least once, even though the condition is false.\n";
$attempts++;
} while ($attempts < 5);
This behavior makes do-while useful in specific scenarios, such as displaying a menu at least once before checking whether the user wants to continue, or validating input where you need to prompt the user before checking their response.
The for Loop
A for loop is ideal when you know in advance exactly how many times you want to repeat something. It combines initialization, condition checking, and incrementing into a single compact line.
php
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . "\n";
}
// Output: 1 2 3 4 5
Breaking down the three parts inside the parentheses:
Part Example Purpose ------------------------------------------------------------ Initialization $i = 1 Runs once, before the loop starts Condition $i <= 5 Checked before every repetition Increment $i++ Runs after every repetition
for loops are especially common when working with arrays by index, or when generating a fixed number of repeated elements:
php
<?php
for ($row = 1; $row <= 3; $row++) {
echo "<p>Row number $row</p>";
}
The foreach Loop
foreach is specifically designed for looping through arrays, and it's by far the most commonly used loop in real-world PHP code, since so much of web development involves working with lists of data.
php
<?php
$fruits = ["Apple", "Banana", "Mango"];
foreach ($fruits as $fruit) {
echo $fruit . "\n";
}
// Output: Apple Banana Mango
Unlike for, foreach doesn't require managing an index variable manually — it automatically moves through each element in the array. For associative arrays, foreach can also give you access to both the key and the value:
php
<?php
$user = [
"name" => "Rohan",
"age" => 28,
"city" => "Mumbai"
];
foreach ($user as $key => $value) {
echo "$key: $value\n";
}
// Output:
// name: Rohan
// age: 28
// city: Mumbai
This key-value form of foreach is extremely common when displaying database results or configuration data, where each piece of information has a meaningful label attached to it.
Choosing the Right Loop
Situation Best Loop ------------------------------------------------------------ Looping through an array foreach Repeating a fixed, known number of times for Repeating until a condition becomes false, while number of repetitions unknown in advance Code must run at least once regardless do-while of the condition
Controlling Loops: break and continue
Two keywords give you finer control over how a loop behaves during execution.
break: Exiting a Loop Early
break immediately stops the loop entirely, regardless of whether the original condition would still be true.
php
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break;
}
echo $i . "\n";
}
// Output: 1 2 3 4
This is useful when you've found what you're looking for and there's no reason to keep checking the remaining items — for example, stopping a search through a list once a match is found.
continue: Skipping to the Next Iteration
continue skips the rest of the current pass through the loop and moves directly to the next one, without stopping the loop entirely.
php
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 2 == 0) {
continue; // skip even numbers
}
echo $i . "\n";
}
// Output: 1 3 5 7 9
Here, whenever $i is even, continue skips the echo line for that iteration but the loop keeps running for the remaining numbers.
Nested Loops
Loops can be placed inside other loops, commonly used for working with grids, tables, or multi-dimensional data.
php
<?php
for ($row = 1; $row <= 3; $row++) {
for ($col = 1; $col <= 3; $col++) {
echo "Row $row, Col $col | ";
}
echo "\n";
}
When using break or continue inside nested loops, they only affect the innermost loop by default. PHP allows specifying a number after break or continue (like break 2) to affect an outer loop instead, though this is used sparingly since it can make code harder to follow.
A Common Real-World Example: Looping Through Database Results
While this series hasn't covered databases yet, it's worth seeing how naturally foreach fits into a realistic scenario you'll encounter constantly once you start working with dynamic data:
php
<?php
$products = [
["name" => "Laptop", "price" => 55000],
["name" => "Mouse", "price" => 500],
["name" => "Keyboard", "price" => 1200],
];
foreach ($products as $product) {
echo $product['name'] . " - Rs. " . $product['price'] . "\n";
}
This pattern, looping through an array of associative arrays, is essentially what happens every time a PHP application displays a list of items pulled from a database.
What's Next
With loops and functions both covered, you now have the core tools to process and repeat logic efficiently. The next step is learning about arrays in depth, since loops and arrays are used together constantly in real PHP applications.