When we write programs, there will be scenarios where we want to execute a statement only if some conditions satisfied. In such situations, we use conditional statements.
In this article, we discuss about decision-making code using if..elseif..else statements in PHP.
Read Also: PHP Math Functions
PHP Conditional Statements
Like most programming languages, PHP also allows one to write code that performs different actions based on logical and comparative conditions during execution. It means we can create test conditions in the form of expressions that evaluates true or false.
In PHP, there are different types of conditional statements.
- If Statement
- If..else statement
- If..elseif..else statement
If Statement
The PHP if statement is the most straightforward conditional statement.The if statement is useful to execute a block of code only if the specified condition is true. In simple words, when we want to execute some code when a condition is true, then we use an if statement.
Syntax
if (condition){ //code to be executed }
Example
<?php $num = 12; if($num<100){ echo “$num is less than 100”; } ?>
Output
12 is less than 100
If-else Statement
The PHP if-else statement executes whether the condition is true or false. The if-else statement is different from if statement. We can enhance the decision-making process by an alternative, adding an else statement to if. To execute some block of code when the condition is true, and some other code is false, then we use the if..else statement.
Syntax
if(condition){ //code to be executed }else{ //code to be executed }
Example
<?php $num=12; if($num%2==0){ echo “$num is even number”; }else{ echo “$num is an odd number”; } ?>
Output
12 is even number
If-elseif-else Statement
The if..elseif is a combination of if and else statement. It is a unique statement that is useful to combine multiple if-else statements so we can check multiple conditions using this statement. When we want to execute different codes for different sets of conditions and have more than two conditions, we will use if..elseif..else statement.
Syntax
if(condition1){ //Executes if condition 1 is true }elseif(condition2){ //Executes if condition 1 is false and condition 2 is true }else{ //Executes if condition 1 and condition 2 both are false }
Example
<?php $d = date("D"); if($d == "Fri"){ echo "Have a nice weekend!"; }elseif($d == "Sun"){ echo "Have a nice Sunday!"; }else{ echo "Have a nice day!"; } ?>
Output
Have a nice weekend!
Read More: PHP Switch and Continue Statements
Conclusion
In this post, we learnt essential conditional statements like if, if-else, if-elseif-else. I hope you have a great understanding of PHP conditional statements.