The else Statement
Pair an if with else when you also want something to happen if the condition turns out to be false.
If Else
The script greets you according to the current hour: before 20 you see "Have a good day!", and from 20 onwards you see "Have a good night!":
Output: PHP script
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
Syntax
An if...else statement has this form:
<?php
if (condition) {
// code to be executed if condition is true;
} else {
// code to be executed if condition is false;
}
?>
The elseif Statement
Two outcomes are not always enough. For more than two conditions, add elseif, which, as its name suggests, combines if and else: it is tested only when the conditions before it were false.
If Elseif Else
The greeting now has three possibilities. Before hour 10 it is "Have a good morning!", before hour 20 it is "Have a good day!", and later than that it is "Have a good night!":
Output: PHP script
<?php
$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!";
}
?>
Syntax
Adding an elseif gives this if...elseif...else form:
<?php
if (condition) {
// code to be executed if this condition is true;
} elseif (condition) {
// code to be executed if first condition is false and this condition is true;
} else {
// code to be executed if all conditions are false;
}
?>
Multiple elseif
There is no limit on the number of elseif blocks in one statement.
Multiple Elseif Example
Here each weekday gets its own message, and the final else covers the weekend:
Output: PHP script
<?php
$d = date("D");
if ($d == "Mon") {
echo "Today is Monday";
} elseif ($d == "Tue") {
echo "Today is Tuesday";
} elseif ($d == "Wed") {
echo "Today is Wednesday";
} elseif ($d == "Thu") {
echo "Today is Thursday";
} elseif ($d == "Fri") {
echo "Today is Friday";
} else {
echo "It is the weekend!";
}
?>