PHP IF ELSE statement, script and example codePHP 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.
We can add ELSE condition to the above statement and that part will be executed once the if condition does not satisfy.
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.
elseifInstead of using else we can use elseif to check more conditions. Here is another example
Once all the conditions are False the last line is executed.
Difference between SWITCH and IF condition checkingWhen 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.