A conditional chooses which code should run for the current state. Good branches make business rules visible and keep invalid input away from the main path.
Use if for ranges or combined conditions, match for one value mapped to one result, and guard clauses to stop early when a requirement fails.
<?php
$orderTotal = 850;
if ($orderTotal >= 1000) {
$delivery = 'Free';
} elseif ($orderTotal >= 500) {
$delivery = 'Reduced';
} else {
$delivery = 'Standard';
}
echo $delivery;
Reduced
A guard clause handles an invalid or exceptional case first, then returns or throws. This keeps the successful path less deeply nested.
<?php
function lineTotal(float $price, int $quantity): float
{
if ($quantity < 1) {
throw new InvalidArgumentException('Quantity must be positive.');
}
return $price * $quantity;
}
echo lineTotal(99.5, 2);
199
switch is a statement and needs break to prevent fall-through in ordinary cases. match is an expression, compares strictly, returns a value, and does not fall through.
A match without a matching arm throws UnhandledMatchError unless a default arm exists.
<?php
$status = 'paid';
$label = match ($status) {
'pending' => 'Awaiting payment',
'paid' => 'Ready to ship',
'cancelled' => 'Closed',
default => 'Unknown status',
};
echo $label;
Ready to ship
PHP converts values to Boolean in a condition. The values false, 0, 0.0, an empty string, the string "0", an empty array, and null are falsey. A non-empty string such as "false" is truthy, so validate external text instead of relying on its appearance.
switch compares case values loosely, while match uses strict identity. That difference matters when form and query values arrive as strings: the integer 0 and string "0" may enter the same switch case but different match arms.
| Decision Shape | Use | Reason |
|---|---|---|
| Ranges or combined predicates | if / elseif | Each branch can express a different condition. |
| Several statements with intentional fall-through | switch | Case flow can be shared when documented. |
| One input mapped to one value | match | Strict comparison, no fall-through, and a returned value. |
| Invalid prerequisite | guard clause | Stops the rejected path before main work. |
0 of 2 checked
Try this next
0 of 2 completed
Explore 500+ free tutorials across 20+ languages and frameworks.