PHP Conditionals and Decision Making
Conditionals choose which code runs. The syntax is simple; the important part is expressing business rules clearly and avoiding truthiness surprises.
On This Page
If, Elseif, and Else
<?php
declare(strict_types=1);
$score = 87;
if ($score >= 90) {
$grade = 'A';
} elseif ($score >= 80) {
$grade = 'B';
} elseif ($score >= 70) {
$grade = 'C';
} else {
$grade = 'Needs work';
}
echo $grade;
Conditions are evaluated from top to bottom. Put the most specific conditions before broader ones.
Prefer Strict Comparison
| Operator | Meaning |
|---|---|
=== | Same value and same type |
!== | Different value or different type |
>, <, >=, <= | Numeric or comparable ordering |
<?php $value = '0'; var_dump($value == false); // true because of coercion var_dump($value === false); // false because the types differ
Combining Conditions
<?php
declare(strict_types=1);
$isAuthenticated = true;
$role = 'manager';
$accountActive = true;
if ($isAuthenticated && $accountActive && in_array($role, ['admin', 'manager'], true)) {
echo 'Access granted.';
}
Use parentheses when an expression mixes && and ||. The small cost in typing is worth the improved readability.
Use Match for Value Mapping
<?php
declare(strict_types=1);
$status = 'past_due';
$message = match ($status) {
'active' => 'The account is active.',
'past_due' => 'Payment is required.',
'suspended' => 'The account is suspended.',
default => 'The account status is unknown.',
};
echo $message;
match uses strict comparison, returns a value, and does not fall through between branches.
Guard Clauses Reduce Nesting
<?php
declare(strict_types=1);
function cancelTrip(Trip $trip, User $actor): void
{
if (!$actor->can('trip.cancel')) {
throw new AuthorizationException('Permission denied.');
}
if ($trip->isCompleted()) {
throw new DomainException('A completed trip cannot be cancelled.');
}
if ($trip->isCancelled()) {
return;
}
$trip->cancel($actor->id());
}
Early exits keep the successful path easy to see and make invalid states explicit.
Real-World Example: Quote Approval
<?php
declare(strict_types=1);
function approvalRoute(int $amountCents, bool $hasPricingOverride): string
{
if ($amountCents < 0) {
throw new InvalidArgumentException('Amount cannot be negative.');
}
return match (true) {
$hasPricingOverride => 'owner_review',
$amountCents >= 500_000 => 'manager_review',
default => 'automatic',
};
}
Common Mistakes
- Using assignment inside a condition by mistake:
if ($status = 'active'). - Comparing unnormalized user input directly to internal values.
- Writing a long chain of role checks instead of a permission policy.
- Using truthiness where
0,'0', an empty array, andnullhave different meanings. - Hiding a button without enforcing the same permission on the server.
