New: Complete Beginner's Guide to Coding is now available in Premium
Updated: Indian Govt Exam roadmaps now include salary breakdowns & timelines
Tip: Use the Career Hub to explore all career paths in one place
Tutorials PHP PHP Loops

PHP Loops

PHP

Loops repeat a block of code multiple times. PHP has 4 types of loops:

  • for — when you know how many times to loop
  • while — loops while a condition is true
  • foreach — loops through arrays (most used!)
  • do...while — runs at least once
Example — PHP
<?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>";
}
?>
Result
Counting: 1 2 3 4 5

Fruits:
🍎 Apple
🍎 Banana
🍎 Mango

Interview Questions — PHP Loops

5 questions commonly asked in interviews

Q1 What are loops in PHP? Beginner

Loops are used to execute the same block of code repeatedly until a condition is met.

Q2 What are the main loop types in PHP? Beginner

PHP supports for, while, do while, and foreach loops.

Q3 What is foreach loop used for? Beginner

foreach is mainly used to loop through arrays.

Q4 Difference between while and do while? Intermediate

while checks the condition before running, while do while runs the code at least once before checking.

Q5 What is break in loops? Intermediate

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

0 / 5
Q1 Which loop is used for arrays?
Q2 Which keyword stops a loop?
Q3 Which keyword skips current iteration?
Q4 Which loop runs at least once?
Q5 Which loop is best when count is known?

More on PHP Loops

Cheatsheet, tips, resources & what to learn next

Quick Cheatsheet

For Loop
for($i = 0; $i < 5; $i++){ echo $i; }
While Loop
while($i < 5){ echo $i; $i++; }
Do While
do { echo $i; $i++; } while($i < 5);
Foreach
foreach($items as $item){ echo $item; }
Break
if($i == 3){ break; }

Pro Tips

1

Use foreach for arrays.

2

Use for loop when total count is known.

3

Always update loop variables to avoid infinite loops.

4

Use break carefully to stop loops.

5

Use continue when you want to skip one iteration.

Up Next

PHP Arrays PHP Functions PHP Forms PHP Sessions PHP Database