Conditionals: if, else, and switch

Learn PHP /Fundamentals /Lesson 6 of 12 /PHP 8.3 in your browser
In this lesson you’ll learn to
  • Branch your code with if, elseif, and else
  • Pick between many options with switch or match, and predict which values count as true

So far your scripts have run straight through, top to bottom, doing the same thing every time. Real programs need to make decisions: show a discount if the cart is big enough, greet a user if they are logged in, print “pass” or “fail” depending on a score. That is what conditionals do. They let your code pick a path.

This builds on Operators, where you learned the comparison operators like ==, >, and === that ask true-or-false questions.

The if Statement

An if statement runs a block of code only when a condition is true. The shape is always the same: the keyword if, a condition in parentheses, then a block in curly braces.

<?php
$score = 75;
if ($score >= 50) {
    echo "You passed";
}
You passed

Read it out loud: “if score is greater than or equal to 50, print You passed.” The condition $score >= 50 is one of the comparisons from the last lesson, and it produces a boolean, either true or false. When it is true, the code in the braces runs. When it is false, PHP skips the braces entirely and moves on. Change $score to 30 and run it again: nothing prints, because the condition is false.

else and elseif

Often you want a fallback: do one thing when the condition is true, and something else when it is false. That is what else is for. And when there are more than two paths, elseif lets you test another condition.

<?php
$score = 72;
if ($score >= 90) {
    echo "Grade A";
} elseif ($score >= 70) {
    echo "Grade B";
} else {
    echo "Keep practicing";
}
Grade B

PHP checks the conditions from top to bottom and takes the first one that is true, then skips the rest. Here 72 >= 90 is false, so it moves on. 72 >= 70 is true, so it prints “Grade B” and stops. The final else has no condition; it is the catch-all that runs when every test above it failed. You can have as many elseif branches as you like, but only one runs.

Order matters in an if chain. Because PHP takes the first true branch, put the strictest test first. If you checked $score >= 70 before $score >= 90, a score of 95 would match the 70 branch first and never reach the A grade.

Truthy and Falsy

A condition does not have to be a comparison. You can put a single value in the parentheses, and PHP decides whether it counts as true or false. Most values are “truthy,” but a short, fixed list of values are “falsy,” meaning PHP treats them as false. Learn this list, because it catches everyone eventually. These values are falsy:

  • The integer 0 and the float 0.0
  • The empty string "" and the string "0"
  • null
  • false itself
  • The empty array []

Everything else is truthy: any other number, any other text, a non-empty array. The one that surprises people is the string "0". It looks harmless, but PHP counts it as false. Make a prediction before you run it.

What does this print?

<?php
if ("0") {
    echo "yes";
} else {
    echo "no";
}
  • no
  • yes
  • 0

The string "0" is on the falsy list, so the condition is false and the else branch runs. The string "00" or "0.0", by contrast, would be truthy, because only the single-character "0" is special.

The string “0” is falsy. This bites people who check user input. If a form field could hold the text "0", a plain if ($input) will treat it as empty and skip your code. When you need to know whether a value was actually provided, test it explicitly, for example if ($input !== ""), rather than leaning on truthiness.

Choosing With switch

When you are comparing one variable against a list of specific values, a long if/elseif chain gets repetitive. The switch statement is built for exactly this. You give it a value once, then list the cases to match.

<?php
$day = 3;
switch ($day) {
    case 1:
        echo "Monday";
        break;
    case 2:
        echo "Tuesday";
        break;
    case 3:
        echo "Wednesday";
        break;
    default:
        echo "Another day";
}
Wednesday

PHP compares $day against each case in turn. When it finds a match it runs that block, and break tells it to stop and leave the switch. The default case is the catch-all, like else: it runs when nothing else matched. A switch reads much more cleanly than five elseif lines that all compare the same variable.

Do not forget the break. Without it, PHP keeps running straight into the next case, a behavior called “fall-through.” If you dropped the break after case 2, then matching 2 would print “Tuesday” and then also “Wednesday”. A missing break is one of the most common switch bugs, so add it to every case unless you deliberately want the fall-through.

A Look at match

PHP 8 added match, a tidier cousin of switch. It returns a value you can store, it needs no break, and it uses strict comparison (===), so no surprise type juggling. Notice each arm uses => and the whole thing ends with a semicolon, because it is an expression.

<?php
$day = 3;
$name = match ($day) {
    1 => "Monday",
    2 => "Tuesday",
    3 => "Wednesday",
    default => "Another day",
};
echo $name;
Wednesday

You can also list several values on one arm, separated by commas, such as 6, 7 => "Weekend". Reach for match when each branch simply produces a value; reach for switch or an if chain when a branch needs to run several statements.

strict vs loose comparison catches people out. Because match uses === and switch uses ==, they can disagree on the same value. A switch ("1") will run case 1 (loose == treats the string and the number as equal), but a match ("1") will not match an arm of 1 and, with no matching arm and no default, throws an UnhandledMatchError. When your value’s type is not certain, match on values of the same type or add a default arm.

Providing a Fallback: ?? and ?:

A very common decision is simply “use this value if I have one, otherwise fall back to something else.” The null coalescing operator ?? does exactly that: $a ?? $b gives you $a when it is set and not null, and $b otherwise. It also quietly handles an undefined variable or missing array key without a warning, which makes it perfect for reading optional input.

<?php
$name = $_GET["name"] ?? "guest";
echo $name;
guest

The $_GET array holds values from the page’s URL, which you will meet properly later; here it is empty, so $name falls back to "guest" with no undefined-key warning. There is also the shorter ternary ?:, where $a ?: $b gives $a when it is truthy and $b otherwise. The difference matters: ?? only falls back on null (or a missing value), while ?: falls back on any falsy value, so 0, "", and "0" all trigger the fallback. Reach for ?? when you mean “if it is set,” and ?: when you mean “if it is truthy.”

In a switch, what does the break keyword do?

  • Stops the switch so PHP does not fall through into the next case
  • Ends the whole script immediately
  • Skips the current case and tries the next one

A break exits the switch after a matching case runs. Leave it out and PHP continues into the following cases, running their code too.

Your Turn

The variable $number holds 4. Using an if/else, print even when the number divides by 2 with no remainder, and odd otherwise. The remainder operator % from the last lesson is the key: $number % 2 is 0 for even numbers. Then hit Check my answer.

<?php
$number = 4;
<?php
$number = 4;
if ($number % 2 === 0) {
    echo "even";
} else {
    echo "odd";
}

What You Learned

  • if runs a block when its condition is true; elseif adds more tests and else is the catch-all, and only the first true branch runs
  • PHP treats 0, 0.0, "", "0", null, false, and [] as falsy, and everything else as truthy
  • switch compares one value against many cases (remember the break), and PHP 8’s match returns a value using strict comparison with no break

You can now:

  • Branch your code with if, elseif, and else
  • Pick between many options with switch or match, and predict which values count as true

Conditionals let your code choose once. Next you will learn loops, which let it repeat an action as many times as you need.

Comments

Leave a reply

You’ll learn to
  • Branch your code with if, elseif, and else
  • Pick between many options with switch or match, and predict which values count as true
Next: Loops: for, while, and foreach →