How to Use elseif in PHP: Syntax and Examples
In PHP,
elseif is used to check multiple conditions after an initial if statement. It allows you to run different code blocks depending on which condition is true, and it must be placed between if and else blocks.Syntax
The elseif statement in PHP is used to check another condition if the previous if or elseif condition was false. It must be written as one word: elseif. You can have multiple elseif blocks between if and else.
- if: checks the first condition.
- elseif: checks another condition if the previous was false.
- else: runs if none of the above conditions are true.
php
<?php if (condition1) { // code if condition1 is true } elseif (condition2) { // code if condition2 is true } else { // code if none of the above conditions are true } ?>
Example
This example shows how to use elseif to check a number and print if it is positive, negative, or zero.
php
<?php $number = 5; if ($number > 0) { echo "The number is positive."; } elseif ($number < 0) { echo "The number is negative."; } else { echo "The number is zero."; } ?>
Output
The number is positive.
Common Pitfalls
Common mistakes when using elseif include:
- Writing
else ifas two words instead ofelseif(though PHP allows both,elseifis preferred for clarity). - Forgetting to use curly braces
{}which can cause unexpected behavior. - Not ordering conditions properly, which can cause wrong blocks to run.
php
<?php // Wrong way (less clear): if ($a > $b) { echo "a is greater"; } else if ($a == $b) { echo "a equals b"; } else { echo "a is smaller"; } // Right way (preferred): if ($a > $b) { echo "a is greater"; } elseif ($a == $b) { echo "a equals b"; } else { echo "a is smaller"; } ?>
Quick Reference
| Keyword | Purpose | Example Condition |
|---|---|---|
| if | Checks the first condition | $x > 10 |
| elseif | Checks another condition if previous is false | $x == 10 |
| else | Runs if none of the above conditions are true | No condition |
Key Takeaways
Use
elseif to check multiple conditions after an if in PHP.elseif must be written as one word for clarity and proper syntax.Always use curly braces
{} to group code blocks for each condition.Order your conditions carefully to ensure the correct block runs.
You can have multiple
elseif blocks between if and else.