Conditionals let a script make decisions — the same idea from Intro to Programming, with PHP's syntax and a couple of PHP-specific shortcuts worth knowing.
<?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";
}
?>Note PHP uses elseif as one word (though else if as two words also works) — a small but common source of typos coming from other languages.
Cleaner than a long elseif chain when comparing one value against several exact possibilities:
<?php
$day = "Mon";
switch ($day) {
case "Mon":
case "Tue":
case "Wed":
case "Thu":
case "Fri":
echo "Weekday";
break;
case "Sat":
case "Sun":
echo "Weekend";
break;
default:
echo "Not a valid day";
}
?>Don't forget break;
Forgetting break; is one of the most common switch mistakes — without it, execution "falls through" into the next case instead of stopping. Stacking cases with no code between them (like Mon through Fri above) is a deliberate, valid use of that fall-through behavior; forgetting a break where you didn't mean to is the bug.
A compact one-line if/else for simple cases:
<?php
$age = 20;
$status = ($age >= 18) ? "adult" : "minor";
echo $status; // "adult"
?>?? returns the left side if it's set and not null, otherwise the right side — extremely common when reading data that might not exist, like a form field:
<?php
$name = $_GET["name"] ?? "Guest";
echo $name; // "Guest" if no ?name= was in the URL
?>