if else Statement in PHP

In PHP if else statement is used to test condition, when a condition is true and another if the condition is not true. There are various ways to use if statement in PHP.
  • if statement
  • if...else statement
  • if...elseif...else statement
  • switch statement

if statement : It is executed if condition is true.

Syntax :
if(condition){
      code to be executed if condition is true;
}

Example :
<?php 
$num=10; 
if($num>0){ 
      echo "The condition is true"; 

?>

Output :
The condition is true


if...else statement : if...else statement is executed whether condition is true or false.

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

      code to be executed if false;
}

Example :
<?php
$x=20;
if($x==20)
{
      echo "The condition is true";
}
else
{
      echo "The condition is false";
}
?>

Output :
The condition is true


if...elseif...else statement : if...elseif...else statement executes different codes for 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
$day ="Mon";
if ($day == "Mon")
{
echo "Have a nice weekend!";
}
elseif($day == "Sun")
{
echo "Have a nice Sunday!";
}
else
{
echo "Have a nice day!";
}
?>

Output :
Have a nice weekend!

0 Comments