PHP: ループ構造

Computers excel at repetitive work. Loops let you repeat an operation hundreds or thousands of times with just a few lines of code — generating tables, iterating through user lists, calculating totals — all effortless.

1. The while Loop

Repeats as long as a condition is true. Check first, execute later.

PHP
<?php
$i = 1;
while ($i <= 5) {
    echo "Round {$i}<br>";
    $i++;
}
// Outputs rounds 1 through 5
?>

Flowchart:

TEXT 📖 参照専用
Initialize → [Check condition] → true → Execute loop body → Update variable → Go back to check
                       ↓ false
                      Exit
⚠️ Warning: If the condition is always true, you get an infinite loop and your program hangs. Before writing every while, ask yourself: is there code inside the loop that will eventually make the condition false?


2. The do...while Loop

The only difference from while: execute once first, then check. This guarantees the loop body runs at least once.

PHP
<?php
$i = 10;
do {
    echo "Executed!<br>";
    $i++;
} while ($i < 5);
// Even though the condition is false from the start, it still outputs "Executed!" once.
?>
while do...while
Check timing Check first, execute later Execute first, check later
Runs at least once? ❌ May run 0 times ✅ Always at least once
Frequency of use Common Infrequent

3. The for Loop

for combines initialization, condition, and iteration update all in one place — it's the most commonly used loop:

PHP
<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Round {$i}<br>";
}
// Outputs 1 through 5
?>

Three parts:

PHP
for (initialization; condition; action-after-each-iteration) {
    // loop body
}

▶ サンプル: Multiplication Table with for

PHP
<?php
echo "<table border='1'>";
for ($i = 1; $i <= 9; $i++) {
    echo "<tr>";
    for ($j = 1; $j <= $i; $j++) {
        echo "<td>{$j}×{$i}=" . ($i * $j) . "</td>";
    }
    echo "</tr>";
}
echo "</table>";
?>
▶ 試してみよう

4. The foreach Loop

foreach is PHP's most distinctive loop — designed specifically for traversing arrays. Its syntax is so clean it's almost addictive:

PHP
<?php
// Loop through an indexed array (value only)
$fruits = ["apple", "banana", "orange"];
foreach ($fruits as $fruit) {
    echo "{$fruit}<br>";
}

// Loop through an associative array (key + value)
$user = [
    "name" => "John",
    "age" => 25,
    "city" => "New York"
];
foreach ($user as $key => $value) {
    echo "{$key}: {$value}<br>";
}
// name: John
// age: 25
// city: New York
?>
💡 Tip: foreach is the most-used loop in PHP. Memorize two patterns: foreach ($arr as $val) for value only; foreach ($arr as $key => $val) when you need both key and value.


5. break and continue

Keyword Action
break Immediately exits the entire loop — no more iterations
continue Skips the rest of the current iteration and moves to the next one

▶ サンプル: break and continue

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

// continue: skip 5
for ($i = 1; $i <= 10; $i++) {
    if ($i == 5) {
        continue;  // Skip this iteration
    }
    echo $i . " ";
}
// Output: 1 2 3 4 6 7 8 9 10
?>
▶ 試してみよう
💡 Tip: break 2; exits two levels of nested loops, and continue 2; skips the current iteration of the outer loop. The number after break/continue indicates how many nesting levels to affect.


6. Mixing Loops with HTML

The alternative syntax makes loops far more elegant inside HTML templates:

▶ サンプル: Generating an HTML Table with foreach

PHP
<?php
$students = [
    ["name" => "Alice", "score" => 92],
    ["name" => "Bob", "score" => 85],
    ["name" => "Charlie", "score" => 78],
    ["name" => "Diana", "score" => 95],
];
?>

<table border="1">
    <tr>
        <th>Name</th>
        <th>Score</th>
        <th>Grade</th>
    </tr>
    <?php foreach ($students as $s): ?>
    <tr>
        <td><?= $s['name'] ?></td>
        <td><?= $s['score'] ?></td>
        <td>
            <?php if ($s['score'] >= 90): ?>
                🌟 Excellent
            <?php elseif ($s['score'] >= 80): ?>
                👍 Good
            <?php else: ?>
                📚 Keep Trying
            <?php endif; ?>
        </td>
    </tr>
    <?php endforeach; ?>
</table>
▶ 試してみよう

This example shows PHP's core magic — turning array data into a complete HTML table with just a handful of lines.


7. Choosing the Right Loop

Scenario Recommended Loop
Traversing an array foreach
Fixed number of iterations (e.g., 1 to 10) for
Unknown number of iterations, but known condition while
Must execute at least once do...while (rarely used)
Nested 2D array / table traversal Nested for or nested foreach
💡 Tip: In PHP, foreach is the absolute workhorse (you'll traverse arrays constantly). Next comes for for counted loops. while is occasionally used when reading files or database result sets. do...while is almost never used.

❓ よくある質問

Q What's the difference between $i++ and $i += 2 in a for loop?
A $i++ increments by 1 each time. $i += 2 increments by 2 (step size of 2). Use the latter to output only odd or even numbers.
Q When should I use foreach vs. for?
A foreach is only for arrays and objects — its syntax is simpler. Use for when you need precise control over the index and step size in a counting loop.
Q What happens if I modify the array inside a foreach?
A By default, foreach ($arr as $val) works on a copy — modifying $val doesn't affect the original array. If you prepend & to $val (reference), modifications do affect the original. We'll cover this in detail in Lesson 12 (Advanced Functions).

📖 まとめ

📝 練習問題

  1. Use a for loop to output all even numbers from 1 to 100 (hint: step size of 2, or % 2 == 0).
  2. Create an associative array storing 5 friends' names and phone numbers, then use foreach to display them as an HTML table.
  3. Use nested loops to print a pyramid of asterisks: row 1 has 1 star, row 2 has 3, ... row 5 has 9 — center-aligned.
Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%