Sunday 19 May 2013

Lesson 3- if-else statement in PHP


Use of If-else Statement

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
}


For Example:-

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:-



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:-



Figure 2

Hope you enjoyed the article. For any query you can write me mail at info@techaltum.com


No comments:

Post a Comment