PHP if else

If, If…else, elseif

Sometimes we want different actions to be performed for different actions. If, If…Else, and Elseif statements can be used for this purpose. Let’s have a look at each of these statements.


If statement

The most important is the “if” statement. It performs some actions if the specified condition is true. If the condition is not true, then the action will be ignored. The syntax of this statement is as follows:

if (condition) code to be executed if the condition is true;

Let’s see an example.

<html> <body> <?php $str="PHP"; if ($str=="PHP") echo "Condition is true."; ?> </body> </html>

Let’s see what the output of the above script will be.

Condition is true.

The value of str is “PHP”. Hence, we get the above output because the condition is true. If the condition had been false, there would have been no output. Consider the script given below:

<html> <body> <?php $str="Learn PHP"; if ($str=="PHP") echo "Condition is true."; ?> </body> </html>

We will not get any output here because our condition is false. If the action to be performed has more than one statement, all the statements should be enclosed within a pair of curly brackets. Look at the code given below:

<?php $str="PHP"; if ($str=="PHP") { echo "Condition is true."; echo "This will help to understand PHP better."; } ?>

The output will be:

Condition is true.This will help to understand PHP better.

If…else

The “if…else” statement provides an additional advantage. If provides the actions to be performed when the condition is true and when it is false. Let’s look at the syntax:

if (condition) code to be executed if the condition is true; else code to be executed if the condition is false;

Have a look at the following example:

<?php $city = "NJC"; if ($city == "NYC") { echo "Condition is true."; echo "I love NYC!"; } else { echo "Condition is false."; echo "I don't belong to NYC!"; } ?>

Since our condition is false, both the statements after else will be executed. Hence, the output will be:

Condition is false.I don't belong to NYC!

Elseif

The “elseif” statement helps us to check more than one conditions. First look at the syntax and then we will see how it works.

if (condition1) { code executed if condition1 is true; } elseif (condition2) { code executed if condition2 is true; } else { code executed if none of the conditions is true; }

Following example will make it more clear.

<html> <body> <?php $city = "LA"; if ($city == "NYC") { echo "I love NYC!"; } elseif ($city == "LA") { echo "I love LA!"; } else { echo "My city is not there!"; } ?> </body> </html>

The value of city is “LA”, hence, the output will be:

I love LA!

The “elseif” statement allows us to check multiple conditions. There can be multiple elseif statements.

If you have found my website useful, please consider buying me a coffee below 😉