Conditional statements are used to perform different actions based on different conditions.
PHP Conditional Statement
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.
In PHP, the following conditional statements are provided:
• if statement - execute code when the condition is true
• if...else statement - when the condition is true Execute a block of code, and execute another block of code when the condition is not true
• if...else if....else statement - execute a block of code when one of several conditions is true
• switch Statement - Execute a block of code when one of several conditions is true
PHP - if statement
The if statement is used to execute code only when a specified condition is true.
Syntax
if (condition)
{
The code to be executed when the condition is true;
}
If the current time is less than 20, the following example will output "Have a good day!":
<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } ?>Try it»
PHP - if...else statement
if (condition) {
Code to be executed when the condition is true;
}
else
{
Code to be executed when the condition is not met;
}
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!":
<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>Try it »
PHP - if...else if....else statement
if (condition) {
if code to be executed when the condition is true;
}
else if (condition)
{
else if Code to be executed when the condition is true;
}
else
{
Code to be executed when the condition is not true ;
}
#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 10 and less than 20, then output "Have a good day!", otherwise output "Have a good night!":
<?php $t=date("H"); if ($t<"10") { echo "Have a good morning!"; } else if ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>Try it»The following is the flow chart of the nested if...else...elseif structure: