PHP Loops
PHPLoops repeat a block of code multiple times. PHP has 4 types of loops:
for— when you know how many times to loopwhile— loops while a condition is trueforeach— loops through arrays (most used!)do...while— runs at least once
<?php
// For loop
echo "Counting: ";
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
echo "<br><br>";
// Foreach loop (most common)
$fruits = ["Apple", "Banana", "Mango"];
echo "Fruits:<br>";
foreach ($fruits as $fruit) {
echo "🍎 " . $fruit . "<br>";
}
?>
Fruits:
🍎 Apple
🍎 Banana
🍎 Mango
Interview Questions — PHP Loops
5 questions commonly asked in interviews
Loops are used to execute the same block of code repeatedly until a condition is met.
PHP supports for, while, do while, and foreach loops.
foreach is mainly used to loop through arrays.
while checks the condition before running, while do while runs the code at least once before checking.
break is used to stop the loop immediately.
Frequently Asked Questions
Common doubts about PHP Loops
foreach is best for arrays.
Yes, loops can be written inside other loops.
continue skips the current iteration and moves to the next one.
Yes, if the loop condition never becomes false.
foreach is mainly used for arrays and iterable objects.
Test Your Knowledge
5 questions · Earn 50 XP
More on PHP Loops
Cheatsheet, tips, resources & what to learn next
Quick Cheatsheet
for($i = 0; $i < 5; $i++){ echo $i; }
while($i < 5){ echo $i; $i++; }
do { echo $i; $i++; } while($i < 5);
foreach($items as $item){ echo $item; }
if($i == 3){ break; }
Pro Tips
Use foreach for arrays.
Use for loop when total count is known.
Always update loop variables to avoid infinite loops.
Use break carefully to stop loops.
Use continue when you want to skip one iteration.