1. PHP conditional statements
are used to perform different actions according to different conditions
In future study and work, it is often necessary to perform different actions for different judgments. Actions. We can use conditional statements in our 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 - executes a block of code when a condition is true, and executes another block of code when the condition is not true
if...else if....else statement - among several conditions Execute a block of code when one is true
switch statement - execute a block of code when one of several conditions is true
2. If statement
The if statement is used to execute code only when the specified condition is true.
The syntax is:
If (condition){
The code to be executed when the condition is true;
}
Example:
<?php //定义应该变量 $score = 61; if($score>60){ echo "恭喜你,及格了"; } ?>
Note: There is no semicolon after the "}" sign in this structure
##3. If...else statement
If the requirement becomes to execute a piece of code when the condition is true, and to execute another piece of code when the condition is not true, you need to use the if...else statement. The syntax is: if (condition){
Code executed when the condition is true;
}
else
{
If the condition is not true The code that is executed when;
}
<?php //取1-10之间的一个随机整数 $x=rand(1,10); //判断整数是否大于等于4 if($x>=4){ echo "恭喜你,中大奖了"; }else{ echo "很遗憾,再来一次吧"; } ?>You have a 70% chance of winning, come and try it now
4. if...else if....else statement
Now the need is to execute a code block when one of several conditions is true, please use if...else if. ..else statement. Syntax: if (condition){
if code executed when the condition is true;
}
else if (condition)
{
elseif Code executed when the condition is established;
}
else
{
Code executed when the condition is not established;
}
<?php //取1-10之间的一个随机整数 $x=rand(1,10); //判断整数是否在指定的范围内 if($x>=9){ echo "恭喜你,中了一等奖"; }else if($x>=7){ echo "恭喜你,中了二等奖"; }else if($x>=4){ echo "恭喜你,中了二等奖"; }else{ echo "很遗憾,再来一次吧"; } ?>There are four kinds of output results. You can try it yourself to see the output. ResultNote: There can be spaces or no spaces between if else
5. Switch statement
The switch statement will be in the next Chapter explanation