PHP If...ElseStatements
Conditional statements are used to perform different actions based on different conditions.
PHP Conditional Statements
When you are writing code, you often need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this task.
In PHP, the following conditional statements are provided:
- if statement- Executes code when the condition is true
- if...else statement- Executes a block of code when the condition is true, and another block of code when the condition is not true
- if...elseif....else statement- Executes a block of code when one of several conditions is true
- switch statement- Executes a block of code when one of several conditions is true
PHP - if Statement
The if statement is used toexecute code only when the specified condition is true.。
Syntax
if (条件) {
条件成立时要执行的代码;
}
If the current time is less than 20, the following example will output "Have a good day!":
PHP - if...else Statement
Execute a block of code when the condition is true, and another block of code when the condition is not true, use the if....else statement.
Syntax
if (条件) {
条件成立时执行的代码;
} else {
条件不成立时执行的代码;
}
If the current time is less than 20, the following example will output "Have a good day!", otherwise it will output "Have a good night!":
Example
Run example »
PHP - if...elseif....else Statement
To execute a block of code when one of several conditions is true, use the if....elseif...else statement.
Syntax
if (条件) {
if 条件成立时执行的代码;
} elseif (条件) {
elseif 条件成立时执行的代码;
} else {
条件不成立时执行的代码;
}
If the current time is less than 10, the following example will output "Have a good morning!"; if the current time is not less than 10 and is less than 20, it will output "Have a good day!"; otherwise it will output "Have a good night!":
Example
Run example »
PHP - switch Statement
The switch statement will be explained in the next chapter.
Other Extensions