Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials PHP Loops
PHP Intermediate FREE

Loops

Lesson 2 of 17 Intermediate Interactive

Loops let you execute a block of code multiple times. PHP supports four main loop types.

for Loop

Best when you know the number of iterations in advance.

while Loop

Repeats as long as the condition is true. Good when you don't know the count.

do-while Loop

Always executes at least once, then checks the condition.

foreach Loop

Specifically designed for iterating over arrays.

Loop Control

  • break — Exit the loop immediately
  • continue — Skip to the next iteration

Syntax

PHP
<?php
// for loop

for ($i = 0; $i < 5; $i++) {
    echo $i;
}

// while loop

$count = 0;
while ($count < 5) {
    echo $count;
    $count++;
}

// do-while loop

$num = 1;
do {
    echo $num;
    $num++;
} while ($num <= 5);

// foreach loop

$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo $color;
}

// break and continue

for ($i = 0; $i < 10; $i++) {
    if ($i === 3) continue; // skip 3

    if ($i === 7) break;    // stop at 7

    echo $i;
}
?>
PHP Loops
PHP
<?php
// For loop
for ($i = 1; $i <= 5; $i++) {
    echo "Count: $i
";
}

// While loop
$count = 0;
while ($count < 3) {
    echo "While: $count
";
    $count++;
}

// Foreach
$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
    echo "Fruit: $fruit
";
}

// Foreach with key
$person = ["name" => "Alice", "age" => 25];
foreach ($person as $key => $val) {
    echo "$key: $val
";
}
?>

Practice

1
Exercise

Use a for loop to print numbers 1-10, but skip number 5 using continue.

Answer
<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i === 5) continue;
    echo "$i ";
}
?>
2
Exercise

Use a foreach loop to display all values in $students = ["Ali", "Sara", "Ahmad"].

Answer
<?php
$students = ["Ali", "Sara", "Ahmad"];
foreach ($students as $student) {
    echo "$student<br>";
}
?>

Quick Quiz

1

Which loop is best for iterating over an array?

foreach is specifically designed for iterating over arrays in PHP.

2

What does the continue statement do in a loop?

continue skips the rest of the current iteration and moves to the next one.

3

How many times does a do-while loop execute if the condition is initially false?

A do-while loop always executes at least once because the condition is checked after the body.

Interview Questions

A for loop uses an index counter and is best for numeric iterations. A foreach loop iterates over arrays automatically without needing an index. foreach is cleaner for arrays, while for gives you more control over the iteration variable.

Yes. In PHP, you can use break N where N specifies how many nested loop levels to exit. For example, break 2 exits two levels of nested loops. This is useful when you need to exit multiple loops at once from deep nesting.