The if...elseif...else Statement
The if...elseif...else a special statement that is used to combine multiple if...else statements.
if(condition){
// Code to be executed if condition is true
} elseif(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
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!";
}
?>
Output : Have a nice day!
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
$age = 25;
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
}
?>
Output : Adult
Using the ternary operator the same code could be written in a more compact way:
<?php
$age = 15;
echo ($age < 18) ? "Child" : "Adult";
?>
Output : Child
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.
© 2024 Easy To Learning. All Rights Reserved | Design by Easy To Learning