Elseif: Between if and Else
When you have more than 2 outcomes in your decision making, you’re going to need to use the PHP elseif statement. The elseif keyword goes in between the if and the else keywords. Your primary condition is handled by the if statement. If the condition is met inside of the if statement, there’s no point in testing any other conditions. The code that’s inside of the if statement body is executed and the remainder of the elseif/else statements are skipped.
When the condition is not met, PHP will check the elseif statements next. If a condition matches, the code inside of that particular elseif statement body will execute and PHP will skip the remainder of the elseif/else testing.
If no conditions are met, the PHP will execute the code inside of the else statement body.
The anatomy of the if/elseif/else statement looks like this:
<?php if ( conditional expression ) { expression } elseif ( conditional expression ) { expression } else { expression } ?>
Time for a quick example. If we did everything correctly, only one expression will execute inside of the if/elseif/else structure.
<?php $car = "Corvette";if ( $car == "Subaru" ) { echo "Subie Wave"; } elseif ( $car == "Jeep" ) { echo "Jeep Wave"; } elseif ( $car == "Corvette" ) { echo "Corvette Wave"; } else { echo "No Wave"; } ?>
Let’s see what PHP does when evaluating the code above.
- PHP assigns the value Corvette to the $car variable.
- PHP encounters the if statement. It tests to see if the value that’s stored inside of the $car variable is equal to Subaru. Since it’s not, it moves on to the elseif statement.
- It tests to see whether the value that’s stored inside of the $car variable is equal to Jeep. Since it’s not, it moves on to the next statement.
- PHP tests to see whether the value that’s stored inside of the $car variable is equal to Corvette. It is.
- PHP executes the code inside of that elseif statement. PHP outputs Corvette Wave.
- It skips over the else statement since it already found a match.
PHP Tutorial Series
Continue your learning with these articles
What else is there?
Else statements execute when the if statement’s condition evaluates to false. Remember, the expressions inside of the if statement can only execute when the conditional expression evaluates to true.
Elseif: Between if and Else
PHP – P26: elseif Statement
When you have more than 2 outcomes in your decision making, you’re going to need to use the PHP elseif statement. The elseif keyword goes in between the if and the else keywords.
TIRED OF IF/ELSE? HOW ABOUT TERNARY?
The ternary operator is a way to quickly express if/else statements. If the boolean expression evaluates to true, the “if_true” result is displayed, otherwise the “if_false” result is displayed.