PHP: Conditionals

A program doesn't just follow one straight path — it needs to do different things under different conditions. "If the user is logged in, show their profile; if not, show a login button" — that's the essence of conditional logic.

1. The if Statement

The simplest form of decision-making: execute a block of code when a condition is true.

PHP
<?php
$score = 85;

if ($score >= 60) {
    echo "You passed!";
}
?>
💡 Tip: The condition inside if's () is ultimately converted to a boolean. Empty strings, 0, "0", null, and empty arrays are all false — everything else is true. (Review Lesson 4's boolean conversion rules.)


2. if...else Statement

One path when the condition is true, another when it's false:

PHP
<?php
$age = 16;

if ($age >= 18) {
    echo "Welcome!";
} else {
    echo "Minors are not allowed.";
}
?>

3. if...elseif...else — Multiple Branches

PHP
<?php
$score = 85;

if ($score >= 90) {
    echo "Excellent";
} elseif ($score >= 80) {
    echo "Good";
} elseif ($score >= 70) {
    echo "Average";
} elseif ($score >= 60) {
    echo "Pass";
} else {
    echo "Fail";
}
?>
⚠️ Warning: PHP uses elseif (one word), though else if (two words) also works. Both produce the same result, but elseif is the officially recommended form.


4. The switch Statement

When you have many exact-match branches, switch is cleaner than a long chain of if/elseif:

PHP
<?php
$day = "Wednesday";

switch ($day) {
    case "Monday":
        echo "A new week begins!";
        break;
    case "Friday":
        echo "Weekend is almost here!";
        break;
    case "Saturday":
    case "Sunday":
        echo "Enjoy your weekend!";
        break;
    default:
        echo "Keep pushing through the workweek!";
}
?>
Feature Notes
case The value to match against — uses == loose comparison
break Exits the switch — forgetting it causes fall-through to the next case
default Executes when no case matches (optional)
Intentional fall-through Omit break deliberately when multiple cases share one code block
🔥 Common Mistake: Forgetting break causes "fall-through" — the code from the next case runs too! PHP's switch has no automatic break.


5. The match Expression (PHP 8.0)

PHP 8 introduced match, a modern, safer, and more concise alternative to switch:

▶ サンプル: match vs. switch

PHP
<?php
$day = "Wednesday";

$message = match($day) {
    "Monday" => "A new week begins!",
    "Friday" => "Weekend is almost here!",
    "Saturday", "Sunday" => "Enjoy your weekend!",
    default => "Keep pushing through the workweek!",
};

echo $message;  // Keep pushing through the workweek!
?>
▶ 試してみよう

Three major advantages of match over switch:

switch match
Comparison == (loose) === (strict)
Return value None (must use break and assign manually) ✅ Returns the result directly
Fall-through ⚠️ Falls through (needs break) ✅ No fall-through
Default default (optional) default (required, or it throws an error)
Multiple conditions Fall-through trick 'A', 'B' => ... comma-separated

▶ サンプル: match Strict Comparison

PHP
<?php
$code = 200;
$httpCode = "200";  // Note: this is a string

// match uses === strict comparison
$result = match($code) {
    200 => "Success",       // $code === 200 is true
    default => "Other",
};
echo $result;  // Success

// switch uses == loose comparison — both would match
?>
▶ 試してみよう
💡 Tip: On PHP 8.0+, prefer match. Only fall back to switch when you need complex logic inside each case (e.g., multiple statements).


6. Mixing Conditionals with HTML

This is PHP's most common pattern for web pages — use the alternative syntax to make conditionals more readable inside HTML:

PHP
<?php
$isLogin = true;
?>

<!-- Alternative syntax: colon + endif -->
<?php if ($isLogin): ?>
    <div class="user-info">
        <!-- TODO: 替换为实际用户头像图片 -->
        <img src="https://i.pravatar.cc/80">
        <span>Welcome back, John!</span>
        <a href="/logout.php">Log out</a>
    </div>
<?php else: ?>
    <div class="login-btn">
        <a href="/login.php">Log in</a>
    </div>
<?php endif; ?>
Standard Syntax Alternative Syntax (Recommended in HTML)
if () { } if (): ... endif;
if () { } else { } if (): ... else: ... endif;
if () { } elseif () { } else { } if (): ... elseif (): ... else: ... endif;
foreach () { } foreach (): ... endforeach;
while () { } while (): ... endwhile;
for () { } for (): ... endfor;

▶ サンプル: Conditionals + HTML Combined

PHP
<?php
$vip = true;
$balance = 800;
?>

<!DOCTYPE html>
<html>
<body>
    <?php if ($vip): ?>
        <div class="vip-badge">VIP Member</div>
    <?php endif; ?>

    <?php if ($balance > 500): ?>
        <button>Withdraw Now</button>
    <?php elseif ($balance > 0): ?>
        <p>Balance is under $500. Withdrawal unavailable.</p>
    <?php else: ?>
        <p>Balance is zero. Top up to continue!</p>
    <?php endif; ?>
</body>
</html>
▶ 試してみよう
💡 Tip: When writing conditionals inside HTML templates, the alternative syntax (if (): ... endif;) is far more readable than curly braces ({}). With braces you have to count pairings to know where an if ends; endif; makes it instantly obvious.

❓ よくある質問

Q How do I choose between switch and match?
A On PHP 8.0+, prefer match — it's safer (=== strict comparison), more concise (direct return value), and has no fall-through. Use switch only when you need complex multi-statement logic inside each case.
Q What if my if has too many levels of nesting?
A If you're beyond 3 levels of nesting, it's time to refactor. Try: (1) early returns (guard clauses); (2) combining conditions into a single variable; or (3) using match instead of deep if/elseif chains.
Q Is there any difference between else if and elseif?
A No functional difference. elseif is PHP's native keyword (recommended). else if is a nested form. Both work identically.

📖 まとめ

📝 練習問題

  1. Write a grade evaluation program: 90+ = A, 80–89 = B, 70–79 = C, 60–69 = D, below 60 = F. Implement it once with if/elseif and once with match, then compare the two approaches.
  2. Create a simulated web page that uses the alternative syntax to display different content based on a user state: not logged in shows a login button; logged in shows the username and a logout link; logged in AND VIP additionally shows a VIP badge.
  3. Write a leap-year checker: a year is a leap year if it's divisible by 4 but not by 100, or if it's divisible by 400.
Web-Tutorial.com

Web-Tutorial 技術チーム

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

100%