PHP if...else...elseif statement
- Previous Page PHP Operators
- Next Page PHP Switch
Conditional statements are used to execute different actions based on different conditions
PHP conditional statements
When you are writing code, you often want to perform different actions for different decisions. You can use conditional statements in the code to achieve this.
In PHP, we can use the following conditional statements:
- if statement - If the specified condition is true, execute the code
- if...else statement - If the condition is true, execute the code; if the condition is false, execute the other end code
- if...elseif....else statement - Execute different code blocks based on two or more conditions
- switch statement - Select one of multiple code blocks to execute
PHP - if statement
The if statement is used forWhen the specified condition is trueExecute the code.
Syntax
if (condition) { Code to be executed when the condition is true; }
The following example will output "Have a good day!" if the current time (HOUR) is less than 20:
Example
<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } ?>
PHP - if...else statement
Use the if....else statementExecute code when the condition is true,Execute another block of code when the condition is false.
Syntax
if (condition) { Code to be executed when the condition is true; } else { Code to be executed when the condition is false; }
If the current time (HOUR) is less than 20, the following example will output "Have a good day!", otherwise output "Have a good night!":
Example
<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
PHP - if...elseif....else statement
Use the if....elseif...else statement toExecute different code based on two or more conditions.
Syntax
if (condition) { Code to be executed when the condition is true; } elseif (condition) { Code to be executed when the condition is true; } else { Code to be executed when the condition is false; }
If the current time (HOUR) is less than 10, the following example will output "Have a good morning!", if the current time is less than 20, then output "Have a good day!". Otherwise, output "Have a good night!":
Example
<?php $t=date("H"); if ($t<"10") { echo "Have a good morning!"; } elseif ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>
PHP - switch statement
We will learn the switch statement in the next section.
- Previous Page PHP Operators
- Next Page PHP Switch