Conditionals

PHP branches with the familiar if/elseif/else and switch, plus two shorthand operators — the ternary and the null-coalescing operator — that show up constantly in real PHP code.

if / elseif / else

PHP grade.php
<?php
$score = 82;

if ($score >= 90) {
    echo "A";
} elseif ($score >= 80) {
    echo "B";
} elseif ($score >= 70) {
    echo "C";
} else {
    echo "F";
}
?>
Output
B

Note the spelling: PHP uses elseif as one word (though else if as two words also works and behaves the same). Conditions are checked top to bottom, and the first one that's true wins — $score >= 80 is checked, matches, and the rest are skipped entirely.

switch

switch compares one value against several possible matches, and needs a break at the end of each case or execution "falls through" into the next one:

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

switch ($day) {
    case "Sat":
    case "Sun":
        echo "Weekend";
        break;
    case "Wed":
        echo "Hump day";
        break;
    default:
        echo "Weekday";
}
?>
Output
Hump day

Stacking case "Sat": directly above case "Sun": with no break between them is the standard way to share one block of code across multiple matching values — both fall through into the same echo.

Note: switch compares using loose equality (like ==), not strict equality. A case of case 0: could match a string that loosely equals 0 in older PHP behavior — one more reason many developers reach for a chain of strict if/elseif comparisons, or PHP 8's match expression, instead of switch.

The ternary operator

For a simple if/else that just picks between two values, the ternary operator fits on one line:

PHP ternary.php
<?php
$age = 16;
$status = ($age >= 18) ? "adult" : "minor";

echo $status;
?>
Output
minor

condition ? valueIfTrue : valueIfFalse — read it as "if the condition holds, use the first value, otherwise use the second."

The null-coalescing operator

?? returns its left side if that value exists and isn't null, and its right side otherwise — extremely common when reading form data or array values that might not be set:

PHP coalesce.php
<?php
$username = null;
$displayName = $username ?? "Guest";

echo $displayName;
?>
Output
Guest

Unlike accessing an undefined variable directly (which triggers a warning), ?? checks safely — this is the idiomatic PHP way to write $_GET['name'] ?? 'default' when reading data a visitor may or may not have provided, which you'll see again in the Forms & Superglobals lesson.