Conditional Statements
Conditional statements let a PHP script branch its behaviour based on whether an expression evaluates to true or false.
if, elseif, else
PHP's conditional syntax closely mirrors C-style languages, with elseif written as one word (unlike some languages that use two).
$mark = 74;
if ($mark >= 80) {
echo "Distinction";
} elseif ($mark >= 60) {
echo "Merit";
} elseif ($mark >= 50) {
echo "Pass";
} else {
echo "Fail";
}
The Ternary and Switch
The ternary operator offers a compact one-line conditional for simple cases. switch is useful when comparing one variable against several possible exact values.
$status = $isActive ? "Active" : "Inactive";
Common Mistakes
- Writing 'else if' as two words when PHP expects 'elseif' as one word in the standard alternative — both actually work in PHP, but mixing conventions inconsistently hurts readability.
- Forgetting break in a switch case, causing fall-through into the next case.
- Overusing the ternary operator for complex conditions, making code harder to read rather than easier.
- Using assignment (=) instead of comparison (==/===) inside an if condition by mistake.
Professional Tip
Reserve the ternary operator for genuinely simple assignments, like setting a default or toggling between two short strings. For anything with nested logic, a full if/else block stays far more readable.
Your Turn
Write a script that determines a shipping cost based on an order total using if/elseif/else, then rewrite the simplest branch using a ternary operator instead.
Mini Quiz
What must you include at the end of each switch case to prevent fall-through in PHP?
break; statement stops it.