Home >Backend Development >PHP Problem >Detailed explanation of two methods of implementing branch operations in PHP

Detailed explanation of two methods of implementing branch operations in PHP

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-03-26 13:32:521981browse

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.

Detailed explanation of two methods of implementing branch operations in PHP

1.if statement

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 $a15ff212aa63a28ed9f19edc4c0d04faf$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.

2.switch 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn