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:

▶ Example: match vs. switch

Output:

TEXT 📖 Display only
25
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!
?>

Output:

TEXT 📖 Display only
Output displayed

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

▶ Example: match Strict Comparison

Output:

TEXT 📖 Display only
result
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
?>

Output:

TEXT 📖 Display only
Output displayed
💡 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;

▶ Example: Conditionals + HTML Combined

Output:

TEXT 📖 Display only
(HTML page rendered in browser)
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>

Output:

TEXT 📖 Display only
Output displayed
💡 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.

❓ FAQ

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.

📖 Summary

📝 Exercises

  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 Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏