Introduction
Conditional execution of one or more statements is a most important feature of any programming language. PHP provides this ability with its if, else and elseif statements. Primary usage of if statement is as follows −
Syntax
if (expression) statement;
The expression in front of if keyword is a logical expression, evaluated either to TRUE or FALSE. If its value is TRUE, statement in next line is executed, otherwise it is ignored. If there are more than one statements to be executed when the expression is TRUE, statements are grouped by using additional pair of curly brackets,
if (expression){ statement1; statement2; .. }
If another staement or a group of statements are required to be executed when expression is FALSE, else keyword is used and one or more statements (inside another pair of curly brackets) are written below it
if (expression){ statement1; statement2; .. } else { statement3; statement4; .. }
Following example shows typical use of if and else keywords. It also uses readline() function to read keyboard input in command line execution of following code. It receive marks as input and displays result as pass or fail depending on marks>=50 or not.
Example
<?php $marks=(int)readline("enter marks: "); if ($marks>=50){ echo "The result is pass" . "\n"; echo "congratulations" . "\n"; } else{ echo "The result is Fail". "\n"; echo "Better luck next time" . "\n"; } ?>
Output
This will produce following result −
The result is Fail Better luck next time
Many a times, if a condition is false, you may require to check if another condition is fulfilled. In this case, another if statement has to be used in else clause of first if statement. There may be a series of cascaded if - else blocks which makes the program tedious. PHP provides elseif statement to address this problem.
As the keyword indicates, elseif is combination of if and else keywords. It works similar to else keyword, with a little difference. Conditional logic of the code has multiple if conditions. The program flow falls through cascade of elseif conditionals and first instance of elseif expression being true, its block is executed and the execution comes out. Last conditional block is a part of else clause, which will be executed only if all preceding if and elseif expressions are false
Syntax
if (expression){ statement; } elseif (expression){ statement; } elseif (expression){ statement; } . . else{ statement; } }
In following example, elseif statement is used to calculate grade of student based on marks
Example
<?php $marks=(int)readline("enter marks: "); if ($marks<35) echo "fail"; elseif ($marks<50) echo "pass class"; elseif ($marks<60) echo "second class"; elseif ($marks<75) echo "first class"; else echo "distinction"; ?>
Output
This will produce following result −
fail