Tutorials Logic, IN info@tutorialslogic.com

PHP Conditional Statements: if, switch, and match

Branching Rules

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.

if and elseif

  • Conditions are checked from top to bottom.
  • Only the first matching branch in one chain runs.
  • Put the most specific overlapping rule before a broader rule.

Delivery Band

Delivery Band
<?php
$orderTotal = 850;

if ($orderTotal >= 1000) {
    $delivery = 'Free';
} elseif ($orderTotal >= 500) {
    $delivery = 'Reduced';
} else {
    $delivery = 'Standard';
}

echo $delivery;
Output
Reduced

Guard Clauses

A guard clause handles an invalid or exceptional case first, then returns or throws. This keeps the successful path less deeply nested.

Require a Positive Quantity

Require a Positive Quantity
<?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);
Output
199

switch and match

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.

Map a Status with match

Map a Status with match
<?php
$status = 'paid';
$label = match ($status) {
    'pending' => 'Awaiting payment',
    'paid' => 'Ready to ship',
    'cancelled' => 'Closed',
    default => 'Unknown status',
};

echo $label;
Output
Ready to ship

Condition Traps

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.
  • Use === when 0, false, null, or an empty string has a distinct meaning.
  • Calculate an expensive value once instead of repeating the call in several branches.
  • Extract long nested decisions into named functions or guard clauses.
  • Use parentheses to reveal the intended grouping of && and ||.

Choose the Branch Form

0 of 2 checked

Q1. Which construct strictly maps one input value to one returned result?

Q2. Why use a guard clause?

Branching Defects

  • Assignment inside a condition

    Use comparison deliberately and enable static analysis for accidental assignment.
  • Broad rule placed first

    Order overlapping ranges from most specific to most general.
  • Missing switch break

    Add break unless fall-through is intentional and documented.
  • No match default

    Cover every enum case or handle the possible UnhandledMatchError.

Try this next

Model a Decision

0 of 2 completed

  1. Implement a tiered discount with guard clauses and verify negative, zero, threshold-minus-one, threshold, and above-threshold inputs. Order overlapping conditions from invalid and specific cases toward the broad default.
  2. Use match to return Read for GET, Write for POST, and Unsupported by default. Keep the default arm explicit for methods outside the supported set.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.