Phase 1 · PHP FoundationsModule 5~38 min read

Decisions & Control Flow

Make programs choose the right path with clear conditions, guard clauses, match expressions, and safe comparisons.

What you'll learn

Control flow turns facts into behavior. You'll build readable branches, exit invalid paths early, and use PHP's match expression when one value maps to one result.

  • Write boolean expressions and if/elseif/else branches
  • Reduce nesting with guard clauses
  • Use ternary and null coalescing sparingly
  • Choose between switch and match
  • Avoid assignment and loose-comparison bugs

Turn business rules into boolean decisions

entry.php
<?php

$age = 22;
$hasTicket = true;

if ($age < 18) {
    echo 'Adult ticket required.';
} elseif (!$hasTicket) {
    echo 'Please buy a ticket.';
} else {
    echo 'Welcome in!';
}

Conditions are evaluated from top to bottom, and only the first matching branch runs. Prefer direct boolean names such as $hasTicket; they make conditions read like sentences.

Truthiness

PHP converts values such as false, null, 0, 0.0, "", "0", and an empty array to false in a condition. For domain rules, explicit comparisons are usually clearer.

Guard clauses keep the happy path visible

A guard clause handles an invalid or exceptional case immediately. This prevents a pyramid of nested conditions.

discount.php
<?php

function discountFor(float $subtotal, bool $isMember): float
{
    if ($subtotal <= 0) {
        return 0.0;
    }

    if (!$isMember) {
        return 0.0;
    }

    return $subtotal >= 100 ? $subtotal * 0.15 : $subtotal * 0.05;
}

echo discountFor(120, true);

Tip

Put invalid, unauthorized, or missing cases first. After the guards, the remaining code can describe the normal path with less indentation.

Ternary and null coalescing

labels.php
<?php

$isActive = true;
$nickname = null;

$stateLabel = $isActive ? 'Active' : 'Inactive';
$displayName = $nickname ?? 'Anonymous';

echo "{$displayName}: {$stateLabel}";

Use ternary for one small choice between two expressions. Use ?? specifically for a missing or null value. If a compact expression needs nesting, promote it to a named if block.

Choose switch or match

switch is a statement with fall-through behavior unless you break. match is an expression: it returns a value, compares strictly, and does not fall through.

status.php
<?php

$statusCode = 201;

$message = match ($statusCode) {
    200 => 'OK',
    201 => 'Created',
    400 => 'Bad Request',
    404 => 'Not Found',
    default => 'Unknown Status',
};

echo $message;

Key idea

Use match when one input maps to one output. Use if for ranges or unrelated conditions. Reserve switch for cases where its statement-style flow is genuinely useful.

Common branching mistakes

  • Writing if ($status = "paid") assigns instead of compares
  • Using loose comparison before normalizing input
  • Checking broad conditions before specific ones, making later branches unreachable
  • Nesting ternary expressions until business rules become unreadable
  • Forgetting default when unmatched input is possible

Recap & quick check

Key takeaways

  • Order branches from specific or exceptional cases toward the normal path.
  • Guard clauses reduce nesting and keep successful logic readable.
  • Ternary is for a small two-way value choice; ?? is for null or missing data.
  • match returns a value, compares strictly, and never falls through.
  • Normalize inputs and use strict comparisons to avoid coercion bugs.

Quick check

1. What is the main benefit of a guard clause?

2. How does match compare its subject to arms?

3. Which expression is best for a null nickname fallback?