Friday 7 June 2013

Lesson 4- use of And-Or in If-Else

Use of “And” and “OR” in if –Else

When we need to check more than one condition in if-else, then we use “And” and “OR” operator in if else.

Use of “And”

When we need that all condition must be true then we use “And” operator.

For Example

Let’s take the previous example where we calculate gross salary. I am taking the same example here but with some changes. If candidate salary is greater than 10000 and his dept is hr then his pf will be 5% but for other dept the pf will be 2% with all salary.

Solution of this program will be as follows:-

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



The output of this code will be as follows:-



Figure 1

In this example salary is 6000 and dept is hr. as I told that when we use “And” in if else then all condition must be true. so it comes in else part as both condition are not true and it calculate pf 2% and show the gross.

Use of “OR”

As we know that when we use “And” then all condition must be true similarly in “OR” only one condition need to be true.

For Example

Lets take the same example using “OR”

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

The output of this code as follows:-



Figure 2

As you can see that in this situation in both condition one condition is true so its calculate pf 5%

Note: - we can also use && instead of “And” and || instead of “OR”. The code will run perfectly.

Hope you understand this topic.
For any query you can mail me at info@techaltum.com



No comments:

Post a Comment