PHP If...Else
Conditional statements let your program make decisions and run different code depending on whether a condition is true or false. The if statement runs a block of code if its condition is true.
You can extend this with else to run code when the condition is false, and elseif to check multiple conditions in sequence, stopping at the first one that is true.
if (condition) {
// code
} elseif (condition2) {
// code
} else {
// code
}if, elseif, else
if checks a condition; elseif checks another condition if the previous ones were false; else runs when none of the previous conditions were true.
The ternary operator
The shorthand ternary operator (condition ? value1 : value2) lets you write simple if/else logic as a compact expression.
<?php
$age = 20;
if ($age >= 18) {
echo "Adult";
} else {
echo "Minor";
}
?>AdultSince $age is 20, which is >= 18, the if block runs and prints "Adult".
<?php
$score = 75;
echo $score >= 60 ? "Pass" : "Fail";
?>PassThe ternary operator is a compact way to write a simple if/else expression.
Key points
- if runs code when a condition evaluates to true.
- elseif checks additional conditions in order.
- else runs when no previous condition was true.
- The ternary operator ?: is a shorthand for simple if/else logic.
