Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

PHP Loops for, foreach, while, do while: Tutorial, Examples, FAQs & Interview Tips

Loops execute a block of code repeatedly as long as a condition is true. PHP provides four loop types: while, do-while, for, and foreach.

while and do-while Loops

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

while / do-while
<?php
// while loop
$i = 1;
while ($i <= 5) {
    echo "Count: $i\n";
    $i++;
}

// do-while loop - runs at least once
$n = 10;
do {
    echo "n = $n\n";
    $n++;
} while ($n < 5);
// Output: n = 10  (runs once even though 10 < 5 is false)
?>

for Loop

The for loop is ideal when you know the exact number of iterations. It combines initialization, condition, and increment in one line.

for Loop
<?php
// Basic for loop
for ($i = 0; $i < 5; $i++) {
    echo "Item $i\n";
}

// Countdown
for ($i = 5; $i >= 1; $i--) {
    echo "$i ";
}
// Output: 5 4 3 2 1

// Nested loops - multiplication tl-table
for ($row = 1; $row <= 3; $row++) {
    for ($col = 1; $col <= 3; $col++) {
        echo $row * $col . "\t";
    }
    echo "\n";
}
?>

foreach Loop

The foreach loop is designed for iterating over arrays. Use the key => value syntax to access both keys and values.

foreach Loop
<?php
// Indexed array
$colors = ["red", "green", "blue"];
foreach ($colors as $color) {
    echo $color . "\n";
}

// Associative array with key => value
$person = ["name" => "Alice", "age" => 30, "city" => "NYC"];
foreach ($person as $key => $value) {
    echo "$key: $value\n";
}

// break and continue
for ($i = 0; $i < 10; $i++) {
    if ($i === 5) break;    // stop loop at 5
    if ($i % 2 === 0) continue; // skip even numbers
    echo $i . " ";
}
// Output: 1 3
?>
Key Takeaways
  • PHP supports for, while, do-while, foreach, and the alternative syntax (for(): ... endfor;).
  • foreach is the most convenient loop for arrays - it iterates over values or key-value pairs.
  • Use break to exit a loop and continue to skip to the next iteration.
  • break 2 exits two nested loops at once - useful for breaking out of nested structures.
  • The list() function (or [] destructuring) can unpack array values in foreach loops.
  • Avoid modifying an array while iterating over it with foreach - use a copy or index-based loop instead.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.