PHP If else Condition

In this PHP tutorial, today we learn PHP If else Condition with the help of examples.

PHP Conditional statements are used to perform different actions based on the results of a logical or comparative test conditions at run time

PHP Conditional Statements

There are many statements in PHP that you can use to perform different actions which is given below:

  • The if statement
  • The if…else statement
  • The if…elseif….else statement
  • The switch…case statement

Now Let’s start to explain each of these conditions statements see below:

 


 

PHP – The if Statement

The if statement is used to execute some code only if the condition is true.

Syntax:

 

if (condition) {
//code to be executed here
}

Flowchart:

Example

<?php  
$num=50;  
if($num<60){  
echo "$num is less than 60";  
}  
?>  

 

Output:

 

50 is less than 100

 


 

PHP – The if…else Statement

The if…else statement executes some code if a condition is true and another block of code if it is false.

Syntax:

 

if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}

 

Example

<?php  
$num=12;  
if($num%2==0){  
echo "$num is even number";  
}else{  
echo "$num is odd number";  
}  
?>  

 

Output:

 

12 is even number

 


 

PHP – The if…elseif…else Statement

The if…elseif…else a special statement that is used to more than two conditions.

Syntax:

 

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;
}

 

Example

<?php  
$d = date("D");
if($d == "Sat"){
    echo "Have a nice weekend!";
} elseif($d == "Sun"){
    echo "Have a nice Sunday!";
} else{
    echo "Have a nice day!";
}
?>  

 

Output:

 

Have a nice day!

Will will explain about PHP switch-case statement in the next chapter.

Pin It on Pinterest

Shares
Share This