The if-elseif-else statement lets you chain together multiple if-else statements, thus allowing the programmer to define actions for more than just two possible outcomes.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output “Have a good morning!” if the current time is less than 10, and “Have a good day!” if the current time is less than 20. Otherwise it will output “Have a good night!”
<?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!";
}
?>
The following example will output “Have a nice weekend!” if the current day is Friday, and “Have a nice Sunday!” if the current day is Sunday, otherwise it will output “Have a nice day!”
<?php
$d = date("D");
if($d == "Fri")
{
echo "Have a nice weekend!";
}
elseif($d == "Sun")
{
echo "Have a nice Sunday!";
}
else
{
echo "Have a nice day!";
}
?>
Ternary Operator
The ternary operator provides a shorthand way of writing the if…else statements. The ternary operator is represented by the question mark (?) symbol and it takes three operands: a condition to check, a result for ture, and a result for false.
To understand how this operator works, consider the following examples:
<?php
if($age < 18){
echo 'Child'; // Display Child if age is less than 18
} else{
echo 'Adult'; // Display Adult if age is greater than or equal to 18
}
?>
Using the ternary operator the same code could be written in a more compact way
<?php echo ($age < 18) ? 'Child' : 'Adult'; ?>
The ternary operator in the example above selects the value on the left of the colon (i.e. ‘Child’) if the condition evaluates to true (i.e. if $age is less than 18), and selects the value on the right of the colon (i.e. ‘Adult’) if the condition evaluates to false.