PHP if..else and elseif

PHP If..Else Tutorial: Make Code Decisions - Conceptual Image of Decision Making

Purpose of if..else in PHP

The if else is a decision-making statement in PHP and many other programming languages.

The PHP if statement will execute one block of code between two or many options – so taking the decision based at certain given criteria.

Syntax of PHP if statement

If there are only two options then you may use simply if with the else statement.

If the expression in small brackets is true, it will execute the block inside the if statement, otherwise, the else block of code will execute.

if ( $Number == 3 ) {

echo "Display Something, if the Number is 3";

} else {

echo "For any other number, or the condition is false!";

}
Note: You may also use only if without the else statement

If options are more then use if..elseif with else statements. For example:

if ($Month == "Jan")

echo "Execute Jan code";

elseif ($Month == "Feb")

echo "Execute Feb code";

elseif ($Month == "Mar")

echo "Execute March code";

else

echo "Any other month";
Note: If you have multiple lines to execute, enclose each block in curly brackets.

I will explain both with examples in this tutorial, so you may understand how to use if..else with HTML or other web elements, as such PHP is generally used for web-based projects.

A simple example to start with – the if..else

Before going to the user selection-based execution of a block in the if..else statement, in this example, I will simply use a static value to show how it works, to give an idea if you are a beginner.

In the example, I have simply declared a variable and assigned it a numeric value.

$Number = 3; 
if ( $Number == 3 ) {
  echo "The Number is 3, so this part is executed!";
} else {
  echo "The Number is other than 3!";
}

Output:

The Number is 3, so this part is executed!
  • Only, the if..else statement is used in the example.
  • If the given number is 3, it will be evaluated as true in the if statement, so the statement inside the if statement will execute.
  • If it is some other number the PHP else statement part will execute.
  • You may copy the code and try it in your PHP editor.

The PHP elseif statement with select dropdown, div, and CSS

Following is an example to use if with elseif PHP statement.

As you open the demo page, an HTML dropdown will be displayed. In the drop-down, you can select a color.

On the change event of dropdown, the same PHP file is called where I have used the “if with the elseif” statement.

As you select a color from the dropdown, a div with the same color will be displayed.

First, have a look at the demo followed by a little description:

PHP elseif

See online demo and code

In the example, the following block of codes is used in the if and elseif statements of PHP:

<?php

$Color = $_REQUEST["color"];

if ($Color == "red"){

echo "<div style='width:40%;height:300px;background-color:red;'></div>";

}

elseif ($Color == "orange"){

echo "<div style='width:40%;height:300px;background-color:orange;'></div>";

}

elseif ($Color == "yellow"){

echo "<div style='width:40%;height:300px;background-color:yellow;'></div>";

}

elseif ($Color == "green"){

echo "<div style='width:40%;height:300px;background-color:green;'></div>";

}

elseif ($Color == "maroon"){

echo "<div style='width:40%;height:300px;background-color:maroon;'></div>";

}

elseif ($Color == "blue"){

echo "<div style='width:40%;height:300px;background-color:blue;'></div>";

}

elseif ($Color == "pink"){

echo "<div style='width:40%;height:300px;background-color:pink;'></div>";

}

else{

echo ("Select a Color from dropdown");

}

?>

This is how it worked:

  • You can see, first the chosen color is picked by using the $_REQUEST[“color”], and assigned to the $color variable.
  • After that, an if statement is used where the value of the color is checked.
  • If the value is “red” it will display the div of red color by using the echo statement.
  • If orange was selected in the dropdown, the elseif statement after the if statement will be evaluated as true.
  • So the div with the orange color is displayed. If some other color is chosen from the dropdown, it will keep on checking the elseif statements.

Following is the code of HTML for dropdown Where the PHP file is called with the selected color:

<p>

<select onChange="window.location='test.php?color='+this.value">

<option>Select a Color</option>

<option value="red">Red</option>

<option value="orange">Orange</option>

<option value="yellow">Yellow</option>

<option value="green">Green</option>

<option value="maroon">Maroon</option>

<option value="blue">Bluish</option>

<option value="pink">Pink</option>

</select>

</p>

Note that, this example is just to demonstrate the use of if..elseif statements. In real time, you may use JavaScript to change the color of div or some other elements in web page.

A PHP if else example to check email format

In this example of the if..else statement, a user is asked to enter the email address in a textbox.

After entering the email and pressing the submit button, the PHP script will check the format of the email address and display the message accordingly.

 

PHP if else email

Online demo and code

As you submit the button, the textbox value is assigned to $address variable by using the $_POST[‘address’]. This variable is checked in the PHP if else condition to validate the correct email format by using a built-in function, FILTER_VALIDATE_EMAIL:

if(filter_var($address,FILTER_VALIDATE_EMAIL)){

echo "$address email is valid!";

}else{

echo "$address is an invalid email!";

}

If the entered email is correct, the if condition will be true and the echo statement will display the given string. Otherwise, the else statement will execute the given statement.

An example of if..else with foreach loop and arrays

In this example, I will use the if statement with a foreach loop and arrays. For that, a simple numeric array is created with five elements.

The elements are: 5, 10, 15, 20, 25. After that, a foreach loop is used to display those array elements.

The task is to quit the foreach loop as it reaches the value of 15 or more.

$arr_numbers = array(5,10,15,20,25);

foreach($arr_numbers as $i){
    echo $i . "<br />";
    if ($i >=15 ){
        break;
    }
}

Output:

5
10
15

To accomplish that, I simply used an if statement. In the if statement following condition is given:

if ($i >=15 ){

break;

}

So as soon as the value of variable $i reaches 15 (which is the value of the current array element), the break statement will stop the loop, and control will move to the next line outside of the foreach loop.

The complete code is given in the demo page.

An example of nested if statement

In certain scenarios, you may need to check two or more conditions after the first condition is true. In that case, you should perform some action if the first condition is true and then check the second condition by using another if..else inside the first if statement.

Using another if statement inside the first if statement is nested if.

See the following structure:

if ($a == 10){

echo ("The value is 10");

if($b == 20){

echo ("The value of b is 20");

}

}

//closing first if statemnt

else {

echo ("The value of a is not 10");

}
  • So inside the curly brackets of the first if statement, another if statement is used before you close it.
  • This will start nested if where you can check another condition.
  • You may go further to use another nested if inside the second if statement and so on.
  • After using the if statement (with else or elseif) inside the first if, close the curly bracket.
  • There you can use elseif or else that will relate to the first if statement.

Conclusion:

The if..else, elseif statements in PHP are used to make decisions based at some criteria. You have to give an expression in the if statement which is evaluated. If it returns as true, it will perform the given actions otherwise, it will move to the next elseif statement (if provided). If all conditions are false, the else part will execute and after that control will move to the next line of code outside of the if statement.

You may use comparison operators like ==, !=, >, <, <= etc. and logical operators like and, or, &&, || etc. to evaluate a condition.

If you have many elseif blocks then you may consider using the switch statement of PHP.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!