🏠 Home / Hub

🐘 PHP Lesson 03 — Loops

← Back to PHP Menu

1. for Loop

<?php

// Basic for loop
for ($i = 1; $i <= 5; $i++) {
    echo "Line $i<br>";
}

// Countdown
for ($i = 10; $i >= 1; $i--) {
    echo $i . " ";
}

// Generate HTML table with PHP
echo "<table border='1'>";
for ($row = 1; $row <= 3; $row++) {
    echo "<tr>";
    for ($col = 1; $col <= 3; $col++) {
        echo "<td>R{$row}C{$col}</td>";
    }
    echo "</tr>";
}
echo "</table>";

?>
Line 1 Line 2 Line 3 Line 4 Line 5 10 9 8 7 6 5 4 3 2 1

2. while & do...while

<?php

$count = 1;
while ($count <= 5) {
    echo "Count: $count<br>";
    $count++;   // မမေ့နဲ့!
}

?>
Count: 1 Count: 2 Count: 3 Count: 4 Count: 5
<?php

// do...while — runs at least once
$n = 10;
do {
    echo "n = $n<br>";
    $n++;
} while ($n < 5);

?>
n = 10 (runs once even though n>=5)

3. foreach — Array Loop (Most Common!)

<?php

// Indexed array
$fruits = ["apple", "banana", "mango"];

foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}

// With index
foreach ($fruits as $index => $fruit) {
    echo "[$index] $fruit<br>";
}

// Associative array
$person = [
    "name" => "Ko Min",
    "age"  => 25,
    "city" => "Yangon"
];

foreach ($person as $key => $value) {
    echo "$key: $value<br>";
}

?>
apple banana mango [0] apple [1] banana [2] mango name: Ko Min age: 25 city: Yangon

4. break & continue

<?php

// break — loop ကို ရပ်
for ($i = 1; $i <= 10; $i++) {
    if ($i === 6) break;
    echo $i . " ";   // 1 2 3 4 5
}

// continue — skip iteration
for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 === 0) continue;  // skip even
    echo $i . " ";   // 1 3 5 7 9
}

// break 2 — exit 2 levels of loops
for ($i = 0; $i < 3; $i++) {
    for ($j = 0; $j < 3; $j++) {
        if ($j === 1) break 2;   // exit both loops!
        echo "$i,$j ";
    }
}

?>

5. Real-world: HTML ကို PHP Loop နဲ့ generate

<?php
$students = [
    ["name" => "Ko Min", "score" => 95, "grade" => "A"],
    ["name" => "Ma Aye", "score" => 78, "grade" => "B"],
    ["name" => "Ko Kyaw", "score" => 62, "grade" => "C"],
];
?>

<table border="1">
<tr><th>#</th><th>Name</th><th>Score</th><th>Grade</th></tr>
<?php foreach ($students as $i => $student): ?>
  <tr>
    <td><?= $i + 1 ?></td>
    <td><?= htmlspecialchars($student['name']) ?></td>
    <td><?= $student['score'] ?></td>
    <td><?= $student['grade'] ?></td>
  </tr>
<?php endforeach; ?>
</table>
Alternative syntax: foreach ():...endforeach; — HTML ထဲ PHP ရေးတဲ့ အခါ ကြည်လင်တယ်

← PHP 02  |  Next: PHP Lesson 04 → Functions →

📌 Study Checklist