Conditional statements are used to perform different actions based on different conditions. This article discusses the relevant knowledge points of conditional statements in detail.
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 the code when the condition is true
if...else statement - Execute a block of code when a condition is true, and execute another block of code when the condition is not true
if...elseif....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 the 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!":
Example
<?php$t=date("H");if ($t<"20"){ echo "Have a good day!";}?>
Running example»
PHP - if...else statement
Execute a block of code when the condition is true, To execute another block of code when the condition is not true, use the if....else statement.
Syntax
if (condition)
{
Code to be executed when the condition is true;
}
else
{
To be executed when the condition is not true Code;
}
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
<?php$t=date("H");if ($t<"20"){ echo "Have a good day!";}else{ echo "Have a good night!";}?>
Running example»
PHP - if...elseif....else statement
Execute a block of code when one of several conditions is true, please use if. ...elseif...else statement. .
Syntax
if (condition)
{
if code executed when the condition is true;
}
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 example "Have a good morning!" will be output. If the current time is not less than 10 and less than 20, then "Have a good day!" will be output. Otherwise, "Have a good night!" will be output:
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!";}?>
This article explains the relevant knowledge points of conditional statements in detail. For more learning materials, please pay attention to the php Chinese website to view.
Related recommendations:
Related explanations about PHP 5 data types
PHP MySQL operations and methods for reading data
The above is the detailed content of About the operation and use of PHP If...Else statement. For more information, please follow other related articles on the PHP Chinese website!