If ... Else StatementThe If Statement is a way to make decisions based upon the result of a condition. For example, you might have a script that checks if boolean value is true or false, if variable contains number or string value, if an object is empty or populated, etc. The condition can be anything you choose, and you can combine conditions together to make for actions that are more complicated.
Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false. The syntax for If statement looks as follows:
if (condition) {
statements_1
} else {
statements_2
}
Condition can be any expression that evaluates to true or false. If condition evaluates to true, statements_1 are executed; otherwise, statements_2 are executed. statement_1 and statement_2 can be any statement, including further nested if statements.
You may also compound the statements using elseif to have multiple conditions tested in sequence. You should use this construction if you want to select one of many sets of lines to execute.
if (condition_1) {
statement_1
}
[elseif (condition_2) {
statement_2
}]
...
[elseif (condition_n_1) {
statement_n_1
}]
[else {
statement_n
}]
Let's have a look at the examples. The first example decides whether a student has passed an exam with a pass mark of 57:
<?php
$result = 70;
if ($result >= 57) {
echo "Pass <br />";
}
else {
echo "Fail <br />";
}
?>
Next example use the elseif variant on the if statement. This allows us to test for other conditions if the first one wasn't true. The program will test each condition in sequence until:
* It finds one that is true. In this case it executes the code for that condition.
* It reaches an else statement. In which case it executes the code in the else statement.
* It reaches the end of the if ... elseif ... else structure. In this case it moves to the next statement after the conditional structure.
<?php
$result = 70;
if ($result >= 75) {
echo "Passed: Grade A <br />";
}
elseif ($result >= 60) {
echo "Passed: Grade B <br />";
}
elseif ($result >= 45) {
echo "Passed: Grade C <br />";
}
else {
echo "Failed <br />";
}
?>