It allows for conditional execution of code fragments. You can create test conditions in the form of expressions that decides to either true or false and based on these results you can perform certain actions.
There are several statements in PHP that you can use to make decisions:
- The if statement
- The if...else statement
- The if...elseif....else statement
- The switch...case statement
The if Statement:
A block of code only executes if the specified condition evaluates to true.
if(condition){
// Code to be executed
}
#example.php
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
}
?>
The if...else Statement
The if / else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.
if(condition){
// Code to be executed if condition is true
} else{
// Code to be executed if condition is false
}
#example.php
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
The if...elseif...else Statement
The if...elseif...else a special statement that is used to combine multiple if...else statements.
if(condition1){
// Code to be executed if condition1 is true
} elseif(condition2){
// Code to be executed if the condition1 is false and condition2 is true
} else{
// Code to be executed if both condition1 and condition2 are false
}
#Example.php
<?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!";
}
?>