PHP If...Else...Elseif Statements
Conditional statements are used to perform different actions based on different conditions.
1. The if Statement
The if statement executes some code if one condition is true.
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
2. The if...else Statement
The if...else statement executes some code if a condition is true and another code if that condition is false.
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
3. The if...elseif...else Statement
The if...elseif...else statement executes different codes for more than two conditions.
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
4. Short Hand If (Ternary)
To write shorter code, you can use the ternary operator ?.
Syntax: (condition) ? (value if true) : (value if false)
$a = 13;
$b = $a < 10 ? "Hello" : "Good Bye";
echo $b;