Loops in php
Loops are used to execute the same block of code repeatedly as long as a condition is true. php supports while, do...while, for, and foreach loops.
The while Loopâ
Executes code as long as the condition is true:
<?php
$i = 1;
while ($i <= 5) {
echo "Count: $i <br>";
$i++;
}
// Output: Count: 1, Count: 2 ... Count: 5
?>
The do...while Loopâ
Executes the code block once before checking the condition, then repeats while true:
<?php
$i = 1;
do {
echo "Number: $i <br>";
$i++;
} while ($i <= 5);
?>
Key difference: The do...while loop always runs at least once, even if the condition is false from the start.
The for Loopâ
Used when you know in advance how many times to loop:
<?php
for ($i = 0; $i < 5; $i++) {
echo "Item $i <br>";
}
?>
Syntax:
for (initialization; condition; increment) {
// code
}
The foreach Loopâ
Used to loop through arrays:
<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
// Apple, Banana, Cherry
?>
foreach with key => valueâ
<?php
$person = ["name" => "Alice", "age" => 30, "city" => "Delhi"];
foreach ($person as $key => $value) {
echo "$key: $value <br>";
}
// name: Alice
// age: 30
// city: Delhi
?>
Loop Control Statementsâ
breakâ
Exits the loop immediately:
<?php
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
break; // stop at 5
}
echo $i . " ";
}
// 0 1 2 3 4
?>
continueâ
Skips the current iteration and moves to the next:
<?php
for ($i = 0; $i < 10; $i++) {
if ($i % 2 == 0) {
continue; // skip even numbers
}
echo $i . " ";
}
// 1 3 5 7 9
?>
Nested Loopsâ
<?php
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo "$i x $j = " . ($i * $j) . "<br>";
}
}
?>
Loop Comparisonâ
| Loop | Best Used When |
|---|---|
while | Condition checked before each iteration |
do...while | Must run at least once |
for | Number of iterations is known |
foreach | Iterating over arrays or objects |
Alternative Syntaxâ
Like control structures, loops support alternative syntax for use with HTML:
<?php $items = ["Home", "About", "Contact"]; ?>
<ul>
<?php foreach ($items as $item): ?>
<li><?= $item ?></li>
<?php endforeach; ?>
</ul>
Finished reading? Mark this topic as complete.