Like most programming languages, PHP allows you to write code that performs different action based on different conditions.
a very general example of decision making – when a traffic signal is red it means to stop, if green then go. Similarly in PHP, following are the conditional statements:
The if statement is used to execute code only if the specified condition is true.
Example –
if(condition){ //Code to be executed if the condition is true ... }
<?php $day = date("D"); if($day == 'Fri'){ echo "Have a happy weekend!"; } ?>
If…else statement is used to improve the conditional/decision making statements by using alternative choices in else statement.
In If…else statement you are allowed to execute one block of code if the condition is true and another block of code if the condition is false.
Syntax
if(condition){ //Code to be executed only if the condition is true } else{ //Code to be executed only if the condition is false }
The If…elseif…else statement executes multiple if…else conditions. If the condition is true that block of code result as an output.
Syntax
if(condition 1){ //code to be executed if the condition 1 becomes true } elseif(condition 2){ //code to be executed if the condition 2 becomes true } elseif(condition 3){ //code to be executed if the condition 3 becomes true } else{ //code to be executed if none of the conditions are true }