SQL PHP HTML ASP JavaScript articles and free scripts to download
PHP Basic Loops

PHP IF ELSE statement, script and example code

PHP IF statement is popular and is used to check some conditions and accordingly statements are executed. We can control the html display part also by the IF STATEMENT. Here is one simple example of if statement.

$j = 5;
$k = 10;
if ($j < $k){
print "Variable $j value is less  than $k";
}

We can add ELSE condition to the above statement and that part will be executed once the if condition does not satisfy. 

$j = 10;
$k = 5;
if ($j < $k){
print "Variable $j value is less  than $k";  // This line will not be executed
} else{
print "Variable $j value is greater  than $k"; // This line will be executed
}

If we are checking the different values of a variable which can have more than two conditions then for each case using PHP IF STATEMENT for matching conditions  is not a good idea. In such a case  PHP SWITCH STATEMENT  is to be used.  

Difference between SWITCH and IF condition checking

When to use switch and when to use if condition checking in PHP scripts ? Both are available to use but they are to be used at appropriate place. Here are some examples.

Checking the gender of the student and redirecting to appropriate page. Here the gender can be Male or Female. So better to use if condition and base on matching string we can decide.

Day of the week and matching code.
Here based on the day of the week we have to execute matching code block. Better to use switch condition as we know one out of 7 choices available will match.

Deciding pass or fail based on the mark secured by student in a exam
If mark is less than 50 then outcome is fail and if mark is equal to or more than 50 then pass. Here better to use IF condition.

Deciding grade based on the mark
Better to use switch condition as based on different ranges of mark we can decide the grade of the student. Say 50 to 79 is grade C, 80 to 89 grade B and 90 above grade A.

Checking the session of user is logged in or not
Use if condition.

Above examples can give you idea on where to use if condition and where to use switch condition.

One of the important use of PHP IF STATEMENT  is when inside a php script we want to display LOG IN or LOG OUT links.

Be the first to post comment on this article :


Google+
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked



Join Our Email List
Email:  
For Email Newsletters you can trust
HTML . MySQL. PHP. JavaScript. ASP. Photoshop. Articles. FORUM Contact us

©2000-2014 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer