PHP Loops
A loop runs the same block of code again and again, while a condition is true. It saves you from writing the same line many times. PHP has four loops: for, while, do...while and foreach.
for loop
Use for when you know how many times to repeat. It has three parts: a start value, a condition, and a step.
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
?>
Output:
1 2 3 4 5
while loop
The while loop checks the condition first and runs while it is true. Be careful to change the value inside the loop, or it will never stop.
<?php
$i = 1;
$sum = 0;
while ($i <= 5) {
$sum += $i;
$i++;
}
echo "Sum = " . $sum;
?>
Output:
Sum = 15
do…while loop
The do...while loop runs the code at least one time, and then checks the condition.
<?php
$i = 10;
do {
echo $i;
$i++;
} while ($i < 5);
?>
Output:
10
foreach loop
Use foreach to go through all the values of an array. It is the easiest loop for arrays.
<?php
$fruits = ["Apple", "Banana", "Cherry"];
foreach ($fruits as $fruit) {
echo $fruit . "<br>";
}
$user = ["name" => "Robin", "city" => "Delhi"];
foreach ($user as $key => $value) {
echo $key . " = " . $value . "<br>";
}
?>
Output:
Apple
Banana
Cherry
name = Robin
city = Delhi
break and continue
breakstops the loop completely.continueskips the rest of the current round and goes to the next one.
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 3) {
continue; // skip 3
}
if ($i == 6) {
break; // stop at 6
}
echo $i . " ";
}
?>
Output:
1 2 4 5
Nested loops
A loop inside another loop is a nested loop. For every round of the outer loop, the inner loop runs fully.
<?php
for ($row = 1; $row <= 3; $row++) {
for ($col = 1; $col <= 3; $col++) {
echo $row * $col . " ";
}
echo "<br>";
}
?>
Output:
1 2 3
2 4 6
3 6 9
Next chapter: PHP Functions.
| Interview Questions & Answers |
|---|
| How to terminate or break a loop in PHP? |