How to use If Else in Php

In the earlier example we calculated the hra and gross salary.

Suppose there is a policy of company that if salary is greater than 10000 then hra will be 5% of salary but if salary is less than 10000 then hra will be 10%

In this situation we will use if-else statement.



Syntax of if-else


		
if (condition)
{
          Logic when condition true
}
else
{
          Logic when condition false
}
		

Example of If-else

Now implement this example


		
<?php
$sal=12000;
$hra;
$gross_sal;
if($sal>10000)
{
$hra=($sal*5)/100;
$gross_sal=$sal+$hra;
}
else
{
$hra=($sal*10)/100;
$gross_sal=$sal+$hra;
}
echo " The Gross Salary is $gross_sal";
?>

		

In this example we take salary is 12000. Which is greater than 10000. Then it will go in if block and calculate the hra 5%.

The output of this code as follows:-


		
if else in php

		Figure 1
		

Now move to the else-if condition.

Now take the same example in another way. If salary is greater than 10000 then hra will be 5% and if less than hra will be 10%. But if salary is 10000 then hra will be 8%.

Now implement this example:-


		
<?php
$sal=10000;
$hra;
$gross_sal;
if($sal==10000)
{
$hra=($sal*8)/100;
$gross_sal=$sal+$hra;
}
else if($sal>10000)
{
$hra=($sal*5)/100;
$gross_sal=$sal+$hra;
}
else
{
$hra=($sal*5)/100;
$gross_sal=$sal+$hra;
}
echo " The Gross Salary is $gross_sal";
?>

		

The output of this code as follows:-


		
if else statement in php

		Figure 2