LearnContact
Lesson 2220 min read

Conditional Statements

Learn how to make decisions in PHP using if, elseif, else, the ternary operator, the null coalescing operator, and switch.

Introduction

Almost every useful program needs to make decisions: show a discount if the cart total is over a certain amount, greet a user differently depending on the time of day, or reject a form if a required field is empty. PHP gives you several tools for this, and choosing the right one makes your code easier to read.

In this lesson you will learn the classic if/elseif/else chain, nested conditionals, the compact ternary operator, the null coalescing operator for safe fallback values, and the switch statement — plus a preview of the cleaner match expression PHP 8 introduced, which the next lesson covers in depth.

What You Will Learn
  • How to branch logic with if, elseif, and else.
  • How to nest conditionals inside one another.
  • How to write compact conditions with the ternary operator.
  • How the null coalescing operator ?? provides safe fallback values.
  • How switch statements work, and why break matters.

The if Statement

The if statement runs a block of code only when its condition evaluates to true. The condition is any expression that produces a boolean value.

if-basic.php
<?php
$age = 20;

if ($age >= 18) {
    echo "You are an adult.";
}
Output
You are an adult.

If the condition is false, the block inside the braces is simply skipped, and execution continues after it.

if / elseif / else

To handle more than two outcomes, chain elseif blocks between if and a final else. PHP checks each condition in order and runs the first block whose condition is true; else only runs if none of them matched.

grade.php
<?php
$score = 72;

if ($score >= 90) {
    echo "Grade: A";
} elseif ($score >= 75) {
    echo "Grade: B";
} elseif ($score >= 60) {
    echo "Grade: C";
} else {
    echo "Grade: F";
}
Output
Grade: C
Order Matters

PHP stops at the first true condition. If you had written "elseif ($score >= 60)" before "elseif ($score >= 75)", a score of 95 would still incorrectly match the first true branch it reaches, so always order conditions from most specific to least specific.

Nested Conditionals

An if statement can contain another if statement inside it. This is useful when a second decision only makes sense after the first condition is already true.

nested.php
<?php
$isLoggedIn = true;
$role = "editor";

if ($isLoggedIn) {
    if ($role === "admin") {
        echo "Welcome, Admin!";
    } else {
        echo "Welcome, valued user!";
    }
} else {
    echo "Please log in.";
}
Output
Welcome, valued user!

Nesting works well for a level or two, but deeply nested conditionals become hard to read. Combining conditions with && or restructuring the logic often produces cleaner code than nesting five levels deep.

The Ternary Operator

The ternary operator lets you write a simple if/else as a single expression: condition ? valueIfTrue : valueIfFalse. It is most useful for short assignments, not complex branching logic.

ternary.php
<?php
$age = 16;

$status = ($age >= 18) ? "adult" : "minor";
echo "Status: $status";
Output
Status: minor

PHP also supports a shorthand ternary, ?:, which returns the left-hand value if it is truthy, or the right-hand value otherwise.

short-ternary.php
<?php
$nickname = "";

$displayName = $nickname ?: "Guest";
echo $displayName;
Output
Guest
Shorthand Ternary vs Null Coalescing

The shorthand ternary ?: checks truthiness, so 0, "", and false all fall back to the default. It also emits a warning if the variable is undefined. For safely checking "is this null or not set" specifically, use ?? instead, covered next.

The Null Coalescing Operator

The null coalescing operator, ??, returns its left-hand operand if it exists and is not null; otherwise it returns the right-hand operand. Unlike ?:, it does not trigger a warning when the variable is undefined, which makes it perfect for safe fallback values — especially with array keys or form input that might not be set.

null-coalescing.php
<?php
$settings = [
    "theme" => "dark",
];

$theme = $settings["theme"] ?? "light";
$fontSize = $settings["fontSize"] ?? "16px";

echo "Theme: $theme, Font size: $fontSize";
Output
Theme: dark, Font size: 16px

You can also chain multiple ?? operators to try several fallbacks in order, and PHP has a shorthand assignment version, ??=, that only assigns a value if the variable is currently null.

null-coalescing-assign.php
<?php
$username = null;

$username ??= "anonymous";
echo $username;
Output
anonymous

The switch Statement

When you need to compare one value against many possible matches, switch can be clearer than a long elseif chain. Each case is checked using loose comparison (==), and execution "falls through" to the next case unless you explicitly stop it with break.

switch.php
<?php
$day = "Wed";

switch ($day) {
    case "Mon":
        echo "Start of the work week";
        break;
    case "Wed":
        echo "Midweek check-in";
        break;
    case "Fri":
        echo "Almost the weekend!";
        break;
    default:
        echo "Just another day";
        break;
}
Output
Midweek check-in
Do Not Forget break

If you omit break, PHP keeps executing every case below the matching one until it hits a break or the end of the switch. This "fall-through" behavior is a classic source of bugs — always add break (or return) at the end of each case unless fall-through is intentional.

switch-fallthrough-bug.php
<?php
$day = "Wed";

switch ($day) {
    case "Wed":
        echo "Midweek check-in. ";
        // missing break!
    case "Fri":
        echo "Almost the weekend!";
        break;
}
Output (unintended fall-through)
Midweek check-in. Almost the weekend!

Multiple case labels can share the same block by stacking them, which is a clean way to group several values that should behave identically.

switch-grouped-cases.php
<?php
$day = "Sat";

switch ($day) {
    case "Sat":
    case "Sun":
        echo "It's the weekend!";
        break;
    default:
        echo "It's a weekday.";
        break;
}
Output
It's the weekend!

Looking Ahead: match

PHP 8 introduced the match expression as a cleaner alternative to switch. It uses strict comparison by default, never falls through, and directly returns a value instead of requiring you to assign one manually inside each case. The next lesson covers match in detail, including a side-by-side comparison with an equivalent switch statement.

Common Mistakes

Avoid These Mistakes
  • Forgetting break in a switch case and accidentally falling through to the next case.
  • Using = instead of == (or ===) inside a condition, which assigns instead of compares.
  • Overusing the ternary operator for complex logic, making the code hard to read.
  • Reaching for ?: when you actually need ?? to check specifically for null or unset values.
  • Nesting conditionals too deeply instead of simplifying the logic.

Best Practices

  • Order elseif conditions from most specific to least specific.
  • Always include break in switch cases unless fall-through is intentional and commented.
  • Prefer ?? over ?: when checking for null or missing array keys.
  • Keep ternary expressions short and simple; use if/else for anything complex.
  • Consider match (next lesson) for value comparisons in PHP 8 and newer.

Frequently Asked Questions

Does switch use strict comparison?

No. switch compares values with the loose == operator by default, which is one reason PHP 8's match expression (strict === comparison) is often preferred.

What is the difference between ?: and ??

?: (Elvis operator) checks whether the left value is truthy, so 0, "", and false trigger the fallback. ?? checks specifically whether the value is null or undefined, leaving other falsy values untouched.

Can I use elseif and else if (two words) interchangeably?

Yes, both work identically in PHP, though elseif (one word) is the more common convention.

Is it bad to use a ternary operator?

No, ternaries are fine for short, simple conditions. They become a problem only when nested or used for complex logic that hurts readability.

Key Takeaways

  • if/elseif/else lets you branch logic based on conditions checked in order.
  • Conditionals can be nested, but deep nesting hurts readability.
  • The ternary operator (condition ? a : b) is a compact expression form of if/else.
  • The null coalescing operator ?? safely provides a fallback for null or missing values.
  • switch compares a value against many cases but requires break to avoid fall-through.
  • PHP 8's match expression, covered next, offers a safer, more concise alternative to switch.

Summary

Conditional statements are how your PHP programs make decisions. You now know how to branch with if/elseif/else, nest conditions, write compact expressions with the ternary and null coalescing operators, and compare a value against multiple cases with switch — while remembering the classic break pitfall.

Lesson 22 Completed
  • You can write if/elseif/else chains and nested conditionals.
  • You can use the ternary operator and ?? for compact, safe expressions.
  • You understand how switch and break work together.
  • You are ready to learn the PHP 8 match expression.
Next Lesson →

Match Expression