Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP If...Else Statements

PHP If...Else Statements


Conditional statements are used to perform different actions based on different conditions.


PHP 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.

PHP provides the following conditional statements:


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 example below will output "Have a good day!":

Example

Run Example »


PHP - if...else statement

Execute a block of code when the condition is true, and another block when it is false, use the if...else statement.

Syntax

if (条件) {

    条件成立时执行的代码;

} else {

    条件不成立时执行的代码;

}

If the current time is less than 20, the example below will output "Have a good day!", otherwise it will output "Have a good night!":

Example

Run Example »


PHP - if...elseif...else statement

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 example below 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.