PHP Else If

In writing PHP code, it is highly likely that you will be using the if/else and elseif statements quite regularly.

The if/else statement checks for one condition, then if that condition is not met, performs another action.

For example:

$color = “White”;
if($color == “Black”){
echo “My favorite color is black.”;
}
else {
echo “I do not like any other color besides black.”;
}

This bit of code would display:

I do not like any other color besides black.

Why? Well, your condition is if the variable $color equals “Black”, then it will echo “My favorite color is black.”, but because the variable $color equals “White” (anything but “Black”), it echoed “I do not like any other color besides black.”.

The elseif statement takes it one step further in that you can check for multiple conditions.

An example of using the elseif statement can look like:

$color = “White”;
if($color == “Black”){
echo “My favorite color is black.”;
} elseif($color == “White”){
echo “I also like white.”;
}else {
echo “I do not like any other colors besides black and white.”;
}

This bit of code would display:

I also like white.

With the elseif statement, you can check for multiple conditions. In this case, the two conditions are if the $color variable equals either “Black” or “White”. If the variable $color is anything other than “Black” or “White”, it will echo “I do not like any other colors besides black and white.”.

Because the variable $color equaled “White”, the condition for “White” was echoed.

You can have as many elseif statements as you want, for example:

if($color == “Black”){
echo “My favorite color is black.”;
} elseif($color == “White”){
echo “I also like white.”;
} elseif($color == “Yellow”){
echo “I also like yellow.”;
} elseif($color == “Red”){
echo “I also like red.”;
} elseif($color == “Purple”){
echo “I also like purple.”;
}else {
echo “I do not know every color on the planet!”;
}

If you end up with a long else/if statement, you might want to think about using a switch instead.