You now have four ways to make a decision: if, the ternary operator, match and switch. Here is how to choose.
Quick guide
| Situation | Best choice |
|---|---|
| One condition, run some code | if |
| Two outcomes, one value | Ternary ? : |
| One value against many fixed options, returning a result | match |
| Ranges or complex conditions | if / elseif or match (true) |
| Many statements per option | if chain, or call a function from match |
| Legacy code on PHP 7 | switch |
Same problem, three solutions
Convert a status code to text.
<?php
$status = 3;
// 1. if / elseif
if ($status === 1) {
$text = "Pending";
} elseif ($status === 2) {
$text = "Shipped";
} elseif ($status === 3) {
$text = "Delivered";
} else {
$text = "Unknown";
}
// 2. switch
switch ($status) {
case 1: $text2 = "Pending"; break;
case 2: $text2 = "Shipped"; break;
case 3: $text2 = "Delivered"; break;
default: $text2 = "Unknown";
}
// 3. match
$text3 = match ($status) {
1 => "Pending",
2 => "Shipped",
3 => "Delivered",
default => "Unknown",
};
echo "$text, $text2, $text3";
Delivered, Delivered, Delivered
The match version is the shortest, and it cannot fall through by accident.
When if is better
Use if when conditions compare different things, not one value.
<?php
$age = 30;
$isMember = true;
if ($isMember && $age >= 60) {
$price = 50;
} elseif ($isMember) {
$price = 80;
} else {
$price = 100;
}
echo $price;
80
Forcing this into match (true) would work, but it would not read any better.
When an array lookup beats both
If you only map one value to another, a plain array is the simplest tool.
<?php
$labels = [1 => "Pending", 2 => "Shipped", 3 => "Delivered"];
$status = 2;
echo $labels[$status] ?? "Unknown";
Shipped
A short rule
- Start with
if. - If you are comparing one value against several constants and want a result, switch to
match. - If it is just a lookup, use an array.