Branch execution is based on which statement block the conditions are met to execute certain codes. In PHP, branch operations are mainly executed through if and switch statements. Let's take a look with the editor.
One-way condition
if(表达式) { 语句;}
Under one-way conditions, as long as the expression is true, the following statements can be executed. If the expression does not hold, it will not be executed.
$pass=60; $a=40; if($a>=$pass){ echo '恭喜,考试通过'; } echo '代码执行结束!';
Since $a<$pass
, the expression is false, and the output result is: code execution ends!
Bidirectional condition
if(表达式) { 语句1; }else{ 语句2; }
Under the bidirectional condition, if the expression is true, statement 1 will be executed, if the expression is not true , then execute statement 2.
$pass=60; $a=40; if($a>=$pass){ echo '恭喜你!考试通过啦!'; }else{ echo '很遗憾,您的考试没有通过!'; }
Since $a<$pass
, the expression is false, and the output result is: Unfortunately, your exam failed!
Multidirectional conditions
if(表达式1) { 语句1; }elseif(表达式2){ 语句2; }elseif(表达式3){ 语句3; }else{ 语句4; }
Under multidirectional conditions, if expression 1 is true, statement 1 will be executed. If If expression 1 does not hold, then expression 2 is executed. If expression 2 is true, execute statement 2. If it is not true, execute statement 3, and so on until the if
statement is exited.
$a=84; $grade1=60;//低于60不及格 $grade2=75;//及格 $grade3=85;//良好 if($a<$grade1){ echo '不及格'; }elseif($a<$grade2){ echo '恭喜你及格了'; }elseif($a<$grade3){ echo '良好!'; }else{ echo '优秀'; }
Since $a>$grade1
, the expression is false, so $a>$grade2
is executed. However, the expression is not established, so $ is executed. a<$grade3
, the expression is established, and the output result is: good!
Note: The code controlled by the if
statement expression is best enclosed in curly braces, even if it is a statement.
switch(表达式){ case 值 1:语句块1;//case相当于== break; case 值 2:语句块2; break; ....... default:语句块n }
In the switch
statement, the value in the expression will be the same as one of the following case
values , if there is no same value, the default
statement is executed.
<?php switch($i){ case 0:echo"0"; break; case 1:echo"1"; break; case 2:echo"2"; break; default:echo"3"; break; } ?>
Executing the above code will get the result: 0
Note:
The value of the expression is preferably an integer or a string;
Don’t forget the break statement to jump out of the switch statement. Add break after each case statement;
If a case statement is not followed by a statement block, then it means that the content of this statement block is the same as the following;
The statement block after the case does not need { } bracketed.
The above is the detailed content of Detailed explanation of two methods of implementing branch operations in PHP. For more information, please follow other related articles on the PHP Chinese website!