Lessons → PHP Basics → Lesson 5

Loops

PHP
⏱ 18 min read📖 BeginnerNot completed

Loops allow you to execute a block of code repeatedly. PHP has four types of loops — each suited for different situations.

for loop

Best when you know exactly how many times to loop:

PHP
<?php
for ($i = 0; $i < 5; $i++) {
    echo $i . " ";
}
// Output: 0 1 2 3 4

// Count down
for ($i = 10; $i >= 1; $i--) {
    echo $i . " ";
}
// Output: 10 9 8 7 6 5 4 3 2 1
?>

while loop

Runs while a condition is true — use when you don't know how many iterations:

PHP
<?php
$count = 1;
while ($count <= 5) {
    echo $count . " ";
    $count++;
}
// Output: 1 2 3 4 5
?>

do-while loop

Runs at least once, then checks condition:

PHP
<?php
$x = 10;
do {
    echo $x . " ";
    $x++;
} while ($x < 5);
// Output: 10 — runs once even though condition is false
?>

foreach loop

Best for iterating over arrays — the most commonly used loop in PHP/Laravel:

PHP
<?php
$fruits = ["apple", "banana", "cherry"];

foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}
// Output: apple banana cherry

// With key => value
$user = ["name" => "John", "age" => 25, "city" => "Tokyo"];
foreach ($user as $key => $value) {
    echo "$key: $value\n";
}
// Output: name: John, age: 25, city: Tokyo
?>

break and continue

PHP
<?php
// break — exit the loop completely
for ($i = 0; $i < 10; $i++) {
    if ($i === 5) break;
    echo $i . " ";
}
// Output: 0 1 2 3 4

// continue — skip current iteration
for ($i = 0; $i < 10; $i++) {
    if ($i % 2 === 0) continue;  // skip even numbers
    echo $i . " ";
}
// Output: 1 3 5 7 9
?>
💡
foreach is king in Laravel! You'll use foreach constantly in Laravel Blade templates to display lists of data from your database: @foreach($users as $user)
← Previous Lesson Next Lesson →
🧠

Test your knowledge!

Take the PHP Basics quiz.

Take Quiz →