Skip to main content

Loops in php

Ayesha
EditReport

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โ€‹

Video Explanationโ€‹

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โ€‹

Video Explanationโ€‹

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โ€‹

Video Explanationโ€‹

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โ€‹

Video Explanationโ€‹

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โ€‹

LoopBest Used When
whileCondition checked before each iteration
do...whileMust run at least once
forNumber of iterations is known
foreachIterating 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>
Telemetry Integration

Completed working through this block? Sync progress to workspace.