Find a sentence on the Internet: switch has a speed advantage over if, and one is to use the transfer address list method; in addition, the switch usually does not adopt the "comparison-transfer" method in loose circumstances, but uses the dec (sub)-jz command pair, the latter not only shortens the instruction length, but also has an advantage in speed.
Let's verify it.
If... Else statement
If you want to execute some code when a condition is set, and execute other code when the condition is not met, use if .... Else statement.
Syntax
If (condition) // Set Conditions
Code to be executed if condition is true; // if the condition is true, the code is executed;
Else
Code to be executed if condition is false; // if the condition is false, the code is executed.
Instance 1
If the current date is Monday, the following code will output "Happy Monday .", Otherwise, "happy every day" will be output ." :
| The code is as follows: |
Copy code |
<? Php $ D = date ("D"); // variable d value assignment If ($ d = "Mon "){ Echo "Happy Monday! "; } Else { Echo "happy every day! "; } ?>
|
Instance 2
If d is equal to 1, "Number 1" is output; otherwise, "number not 1" is output"
| The code is as follows: |
Copy code |
<? Php $ D = 2; // variable d value assignment If ($ d = 1 ){ Echo "Number 1"; // The output value when the variable d is equal to 1 } Else { Echo "the number is not 1"; // The output value when the value is not 1 } ?> |
Switch statement
Syntax
| The code is as follows: |
Copy code |
Switch (expression) { Case label1: Code to be executed if expression = label1; Break; Case label2: Code to be executed if expression = label2; Break; Default: Code to be executed If expression is different From both label1 and label2; }
|
Instance
Working principle:
Perform a calculation on the expression (usually a variable).
Compare the expression value with the case value in the structure
If a match exists, execute the code associated with the case
After the code is executed, the break statement prevents the code from jumping into the next case for further execution.
If no case is true, use the default statement.
| The code is as follows: |
Copy code |
<? Php Switch ($ x) { Case 1: Echo "Number 1 "; Break; Case 2: Echo "Number 2 "; Break; Case 3: Echo "Number 3 "; Break; Default: Echo "No number between 1 and 3 "; } ?> |
Conclusion 3
1. Two methods in PHP are used to determine whether the value meets the condition. If the condition is met or not, different actions are performed.
2. The shorter the switch step, the higher the efficiency, while the if else is more flexible, suitable for comparing more than one variable ..
3. when the determined value is a variable, ifelse runs more efficiently than switch. ifelse implements the final judgment policy and starts to judge from the first condition until the last else, therefore, it is advantageous to learn to use a switch;