Monday, August 14, 2017

PHP IF ELSE Statement


The if construct is one of the most important features. It allows for conditional execution of code fragments. IF statement first check the condition of the statement, When the condition is :
1. True, it will execute the content of if statement block.
2. false, it will not execute the content of if statement block.






PHP If Statement


PHP if statement is executed if condition is true.

Syntax:
if(condition){  
//code to be executed  
}

Example :
<?php  
$number=12;  
if($number < 150){  
echo "$number is less than 150";  
}  
?>

Output:
--------------
12 is less than 150

PHP If-else Statement

PHP if-else statement is executed whether condition is true or false.
1. When Condition of if statement block is true then it will execute the content of if block.
2. When Condition of if statement block is false then it will execute the content of else block.

Syntax:
if(condition){  
//code to be executed if true  
}else{  
//code to be executed if false  
}

Example :
<?php
$a = 10;
$b = 20; 
if ($a > $b) {
  echo "a is greater than b";
} else {
  echo "a is NOT greater than b";
}
?>

Output:
----------------------------
a is NOT greater than b

PHP else-if Statement

PHP else-if statement is executed whether condition is true or false.
1. When Condition of if statement block is true then it will execute the content of if block.
2. When Condition of if statement block is false then it will check the condition of else-if statement.
     a). When Condition of else-if statement block is true then it will execute the content of else-if block.
     b). When Condition of else-if statement block is false then it will execute the content of else block.

Syntax :
if ( condition)
{
 //code to be executed if true
}
elseif (condition) )
{
 //code to be executed elseif true
}
else
{
 //code to be executed if false  
}

Example :
<?php
$a = 10;
$b =20;

if ($a > $b) {
    echo "a is bigger than b";
} elseif ($a == $b) {
    echo "a is equal to b";
} else {
    echo "a is smaller than b";
}
?>

Output:
-------------------------
a is smaller than b





No comments:

Post a Comment