PHP Conditional Statement (if-else, if-elseif-else)


The Conditional statements are used to decide the flow of execution based on different conditions. If a condition is true, then the code can perform one action and if the condition is false, then it perform another action. In PHP there are two conditional statements :

1. If...Else statement
2. If...ElseIf...Else statement

1. If statement :

The If statement is used to execute a set of code when a condition is true. The syntax of If Statement is :
 if (condition) {
   code to be executed if condition is true
 }
Example :
<?php

  $age = 25;

  if($age > 18) {
    echo "You are an Adult.";
  } else {
    echo "You are a miner.";
  }

?>
Output :

You are an Adult.


2. If...ElseIf...Else statement

The If...ElseIf...Else statement is allows to make a correct decision out of several conditions. Basically it evaluates the if condition and execute a block of code if expression become true, otherwise check the next else if condition and so on. If specified if...Elseif condition does not satisfied, then the else block of code is executed. Syntax :
 if (condition_1) {
   	 code to be executed if condition is true
 } elseif (condition_2) {
       	 code to be executed if condition is true
 } elseif (condition_3) {
	 code to be executed if condition is true
 } else {
	 code to be executed
 }
Example :
<?php

  $num = 60;
  
  if($num < 50) {
    echo "$num is less then 50.";
  } elseif($num < 100) {
    echo "$num is less then 100.";
  } else {
    echo "$num is Greater then 100.";
  }

?>
Output :

60 is less then 100.


Next Topic :