Home >Backend Development >PHP Tutorial >PHP control statement If...Else_PHP tutorial
If, elseif and else statements are used to perform different actions based on different conditions.
Conditional Statements
When you write code, you often need to perform different actions for different judgments. You can use conditional statements in your code to accomplish this task.
if...else statement
Execute a piece of code when the condition is true, and execute another piece of code when the condition is not true
elseif statement
is used in conjunction with if...else to execute a code block when one of several conditions is true
If...Else statement
If you want to execute some code when a certain condition is true and other code when the condition is not true, use the if....else statement.
Syntax
if (condition) code to be executed if condition is true;else code to be executed if condition is false; |
Example
If the current date is Friday, the following The code will output "Have a nice weekend!", otherwise it will output "Have a nice day!":
<?php$d=date("D");if ($d=="Fri") { echo "Hello!<br>"; echo "Have a nice weekend!"; echo "See you on Monday!"; }?> |
ElseIf statement
If you want to To execute code when one of the conditions is true, use the elseif statement:
Syntax
if (condition) code to be executed if condition is true;elseif (condition) code to be executed if condition is true;else code to be executed if condition is false; |
Instance
If current The date is Friday. The following example will output "Have a nice weekend!". If it is Sunday, it will output "Have a nice Sunday!", otherwise it will output "Have a nice day!":
<?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!"; ?> |