Conditional statements are used to perform different actions based on different conditions, and this article details the relevant knowledge points of the conditional statement.
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.
In PHP, the following conditional statements are available:
If statement-executes code when conditions are true
If...else statement-Executes a piece of code when the condition is set, and executes another piece of code when the condition is not true
If...elseif....else Statement-executes a block of code when one of several conditions is established
Switch statement-executes a block of code when one of several conditions is established
Php-if statements
The IF statement is used to execute code only when the specified condition is true.
Grammar
if (condition) {The code to execute when the condition is established;}
If the current time is less than 20, the following instance will output "a good day!" :
Instance
<?php$t=date ("H"), if ($t < ") { echo" has a good day! ";}? >
Running Instances»
Php-if...else statements
Execute a piece of code when the condition is established, and execute another piece of code when the condition is not established, using the If....else statement.
Grammar
if (condition)
{
Code executed when the condition is established;
}
Else
{
Code executed when the condition is not established;
}
If the current time is less than 20, the following instance outputs "a good day!", otherwise the output "has a good night!" :
Instance
<?php$t=date ("H"), if ($t < ") { echo" has a good day! ";} else{ echo "Have a good night!";}? >
Running Instances»
Php-if...elseif....else statements
To execute a block of code when one of several conditions is true, use the If....elseif...else statement:
Grammar
if (condition)
{
The code executed when the condition is established;
}
ElseIf (condition)
{
ElseIf code executed when the condition is established;
}
Else
{
Code executed when the condition is not established;
}
If the current time is less than 10, the following instance will output "a good morning!", if the current time is not less than 10 and less than 20, the output "has a good day!", otherwise the output "has a good night!" :
Instance
<?php$t=date ("H"), if ($t < "ten") { echo "has a good morning!";} ElseIf ($t < ") { echo" has a good day! ";} else{ echo "Have a good night!";}? >
This article explains in detail the relevant knowledge points of the conditional statements, and more study materials are concerned about the PHP Chinese network.