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
$score = 85;
if ($score >= 60) {
echo "You passed!";
}
?>
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
$age = 16;
if ($age >= 18) {
echo "Welcome!";
} else {
echo "Minors are not allowed.";
}
?>
3. if...elseif...else — Multiple Branches
<?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";
}
?>
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
$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 |
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:
25
<?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:
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:
result
<?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:
Output displayed
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
$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:
(HTML page rendered in browser)
<?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:
Output displayed
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
=== 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.else if and elseif?elseif is PHP's native keyword (recommended). else if is a nested form. Both work identically.📖 Summary
if→elseif→elsehandles multi-branch conditional logicswitchworks well for multiple exact matches — rememberbreakto prevent fall-throughmatch(PHP 8+) is safer than switch (===strict comparison, no fall-through, returns directly)- In HTML templates, use alternative syntax (
if (): ... endif;) — it's much more readable than curly braces - When conditions get too numerous, consider
matchor earlyreturnto reduce nesting
📝 Exercises
- Write a grade evaluation program: 90+ = A, 80–89 = B, 70–79 = C, 60–69 = D, below 60 = F. Implement it once with
if/elseifand once withmatch, then compare the two approaches. - 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.
- 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.