In this tutorial, you will learn about PHP if…Else…Elseif Statements. So without much to do, let’s get started.
Conditional statements are used to perform different actions based on different situations.
In this tutorial, you will learn-
In this article, you will learn-
PHP Conditional Statements
Very often whilst you write code, you want to perform different actions for different situations. You can use conditional statements to your code to do that.
In PHP we’ve the subsequent conditional statements:
• if statement- executes some code if one condition is true
• if…Else statement – executes some code if a situation is true and some other code if that situation is false
• if…Elseif…Else statement- executes different codes for more than two conditions
• switch statement- selects one of many blocks of code to be executed
PHP – The if Statement
The if declaration executes some code if one situation is true.
Syntax
if (condition) { code to be executed if condition is true; }
Example
Output “Have a good day!” if the current time (HOUR) is much less than 20:
<!DOCTYPE html> <html> <body> <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } ?> </body> </html>
PHP – The if…Else Statement
The if…Else statement executes some code if a condition is true and any other code if that condition is false.
Syntax
if (condition) { code to be executed if condition is true; } else { code to be executed if condition is false; }
Example
Output “Have a good day!” if the current time is less than 20, and “Have a good night!” otherwise:
<!DOCTYPE html> <html> <body> <?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> </body> </html>
PHP – The if…Elseif…Else Statement
The if…Elseif…Else statement executes different codes for more than two conditions.
Syntax
if (condition) { code to be executed if this condition is true; } elseif (condition) { code to be executed if first condition is false and this condition is true; } else { code to be executed if all conditions are false; }
Example
Output “Have a good morning!” if the current time is less than 10, and “Have a good day!” if the present day time is much less than 20. Otherwise it will output “Have a good night!”:
<!DOCTYPE html> <html> <body> <?php $t = date("H"); echo "<p>The hour (of the server) is " . $t; echo ", and will give the following message:</p>"; if ($t < "10") { echo "Have a good morning!"; } elseif ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> </body> </html>
PHP – The switch Statement
The switch statement will be explained in the next chapter.
READ NEXT
This is about PHP if…Else…Elseif Statements, and we hope you have learned something from this tutorial and share your opinion about this tutorial. What do you think about it, and if you think this tutorial will help some of your friends, do share it with them.