if/else and match
Conditional branching in PHP, from basic if/else to the modern match expression.
2 min read
PHP's conditional logic will look familiar if you've used any C-style language, plus one modern addition — match — that's worth reaching for over a long switch.
if, elseif, else
<?php
$age = 20;
if ($age < 13) {
echo "Child";
} elseif ($age < 20) {
echo "Teenager";
} else {
echo "Adult";
}Conditions are evaluated top to bottom, and the first branch whose condition is true runs — the rest are skipped entirely, even if a later condition would also have been true.
Comparison and logical operators
<?php
$isMember = true;
$hasCoupon = false;
if ($isMember && $hasCoupon) {
echo "20% off";
} elseif ($isMember || $hasCoupon) {
echo "10% off";
}&& (and), || (or), and ! (not) combine conditions. PHP also has and/or as word-based alternatives with lower operator precedence than &&/|| — a common gotcha, since $a = false or true; assigns false to $a (because = binds tighter than or), not the true a beginner might expect. Stick to && and || to avoid the ambiguity entirely.
The ternary and null coalescing operators
<?php
$status = $isActive ? "Active" : "Inactive";
$name = $user['name'] ?? "Guest";The ternary operator (condition ? ifTrue : ifFalse) is a compact if/else for a single value. ?? (null coalescing) returns its left side unless that's null or undefined, in which case it falls back to the right side — commonly used for default values without triggering an "undefined index" warning.
switch: matching one value against many
<?php
$day = "Mon";
switch ($day) {
case "Sat":
case "Sun":
echo "Weekend";
break;
default:
echo "Weekday";
}switch compares $day against each case using loose equality (==), and — critically — execution falls through to the next case unless you break. Stacking case "Sat": case "Sun": with no code between them is how you intentionally share one block across multiple values; forgetting break anywhere else is a classic bug.
match: switch's modern, safer replacement
<?php
$day = "Mon";
$type = match ($day) {
"Sat", "Sun" => "Weekend",
default => "Weekday",
};
echo $type;match (added in PHP 8) fixes switch's sharpest edges: it compares with strict equality (===, no type juggling), never falls through between arms, and is an expression — it directly produces a value you can assign, rather than requiring a variable to be set inside each branch. It also throws an error if no arm matches and there's no default, rather than silently doing nothing. For new code, prefer match over switch whenever you're mapping one value to another.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.