PHP Conditionals and Decision Making
The syntax for conditionals is about as simple as programming gets. The hard parts are writing business rules so someone else can actually read them, and not getting bitten by PHP's ideas about what counts as "true."
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 checked top to bottom and the first match wins, so put the most specific ones first.
Use === (almost always)
| 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.';
}
Whenever you mix && and ||, add parentheses. Even if you know the precedence rules, the next person reading it might not.
match is great for mapping values
<?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, doesn't fall through like switch does, and throws an error if nothing matches. I use it constantly.
Guard clauses beat deep 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());
}
Bail out early on the bad cases and the happy path ends up flat and easy to read, instead of buried five ifs deep.
A real-world example: approving a quote
<?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',
};
}
Mistakes I see a lot
- 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.
