Home >Backend Development >PHP Tutorial >PHP Learning Guide-Chapter 7
Control structure
The focus of this chapter
◆ Establishing and combining logic tests
◆ Using if and switch for branch processing
◆ Using while and for
◆ Using exit and die to exit the execution of the page
It is difficult to write useful programs if you cannot allow the program to determine different executions based on different situations. Simply put, the behavior of the program code that outputs the display variable depends on the value of a certain variable. As a programmer, we can use different actions to make the program respond differently to events (according to the external world, time , user input or database content, etc.).
This kind of program response requires a "control structure". This structure can control instructions that should be executed with different program codes under different circumstances. In the previous chapter, we used control structures like if but didn't really explain it in depth. In this chapter, we will introduce each control structure provided by PHP and study in detail how they work and operate.
For experienced C language programmers: Among all the functions of PHP, the "control" part is the most similar in style to the C language. All the structures originally used in the C language can be used here, and It works the same way. If you are an experienced C language programmer, you can skip ahead and read the sections at the end of this chapter directly.
The two main types of control structures we will discuss are branches and loops. A branch is a fork in the execution path of a program. Depending on a certain test, the program can choose to proceed to the left or to the right. The subsequent paths may be different, or they may merge together again. A loop is one of the branch types that has an execution path that returns to the beginning of the branch and can be tested repeatedly or executed in a loop.
Before you can effectively utilize control structures, you must be able to effectively construct test conditions. We'll start with the simplest tests, learning about the constants TRUE and FALSE, and then use these tests in more complex code.
Boolean operator
Every control structure introduced in this chapter contains two distinct parts: one is the test part (which determines which direction to proceed), and the other is the test code (which is a separate (branch or loop) test is performed through Boolean operation evaluation, and the judgment of "true" or "not true" is the result of the operation expression.
Boolean constants
The simplest operation type is a simple value (simple value), and the simplest Boolean values are TRUE and FALSE constants, and vice versa. For example, we can embed them in the test section of an if-else statement:
if (TRUE)print(“This will always print”); elseprint(“This will never print”); The above example is the same as the following Indeed, the description is the same: if (FALSE) print ("This will never print"); elseprint ("This will always print");
Logical operators
Logical operators can combine other logic (also known as Boolean) value to generate a new Boolean value. PHP supports standard logical operations (and, or, not, and xor). The first two have alternative versions, as shown in Table 7-1.
7-1 Logical operation symbols
For C language programmers, you must be familiar with the "&&" and "||" operators. The "!" operator is often called "NOT", for obvious reasons.
The following expressions are examples of logical operators:
(($statement_1 && $statement_2)||
($statement_1 && ! $statement_2)||
(! $statement_1 && $statement_2)||
(! $statement_1 && ! $statement_2)||
This is a "tautology", which means that no matter what the value of the variable is, the result is true. There are four possible real values of the two variables. Combination, each of which is represented by a "&&" operator. One of these four must be true, because they are connected together by the "||" operator.
The following example. The xor used is a more clever demonstration of "tautology":
(($statement_1 and $statement_2 and
$statement_3) xor
((! ( $statement_1 and $statement_2)) or
(! ( $statement_1 and $statement_3)) or
(! ( $statement_2 and $statement_3))))
The meaning of this operation is: "Given three narrative statements, only one of the following two situations can occur. 1: If all three statements of non-Ne are true, there will be a pair of statements that are not true. "
Priority of logical operators
Compared with any other operator, some logical operators have priority. The order is higher, but you can also use parentheses to change the order of precedence. Logical operators are arranged in a much lower order of precedence than others, so the designated operator (=) is tied more closely than "and". But it is looser than "&&".
There is a complete list of operator precedence and correlation in the online manual at http://www.php.net/
Short-circuiting of logical operators
A very convenient feature of the Boolean operator is that it combines from left to right, and can be designed to "short-circuit" it. If the first parameter is determined to be a true value, there is no need to continue to calculate the second parameter. Parameters. For example, when determining a very approximate ratio of two numbers, but also to avoid possible division by 0 errors, first test to ensure that the divisor is not 0, just use the "!=" (meaning not equal to) operator:
if ($denom != 0 && $numer/ $denome>2)
print(“More than twice as much!”);
When $denom is “0”, regardless of the second operation Whether the expression is true or false, the "&&" operator should return a "not true" value. Because of the short-circuit behavior, the second expression is not evaluated, thus avoiding errors. In the case where $denom is not equal to "0", the "&&" operator does not have enough information to reach a truth conclusion, so the second operator is evaluated.
So far, we have formally discussed the TRUE and FALSE constants, and how to combine them to form other true and false values. Now let's look at the operators that perform actual Boolean arithmetic testing.
Comparison operators
Table 7-2 shows comparison operators, which can be used for numbers or strings (please pay attention to the description of "Be careful with non-integers").
Table 7-2 Comparison operation symbols
The following examples are some variable specifications, followed by a compound test that is always true:
$three = 3; $four = 4; $my_pi = 3.14159; If (($three = =$three) and($four ===$four)and($three !=$four)and($three=$there) and($three $three) and($my_pi ”); elseprint (“Sure you typed that right?
”):
Please note a very common mistake: confusing the specification operator (=) and the comparison operator (==). "if($three = $four).." This statement may accidentally set $three and $four as equivalent variables (types). If $four is true, its test result will be true!
Operator precedence
Although relying too much on precedence can confuse people reading the code, it is still a good idea to note that comparison operators have higher precedence than Boolean operators. Please look at the following example:
If ($small_num> 2 && $small_num
It does not require any more parentheses except the two necessary parentheses for if.
String Comparison
Comparison operators can be used to compare strings or numbers (please pay attention to the description of "Be careful with non-constant numbers"). We want the following program output to show the corresponding example:
if (("Marx"”);}
Be careful with non-integer numbers
Although comparison operators can operate on numbers or strings, you need to pay attention to the following two issues.
First of all, it is generally safe to make a greater than less comparison of a double-precision float (or an integer and a double-precision float), but an equality comparison of a double-precision float can be dangerous, especially Be more careful when comparing the results of numerical calculations. The problem is a "rounding error" that causes two theoretically equal values to be slightly different.
Secondly, although comparison operators can perform comparison operations on strings in the same way as numbers, PHP automatically performs type conversion, so sometimes unexpected results are obtained when interpreting strings as numbers. , for example, the following code:
$strinhg_1 = “00008”; $string _2 = “007”; $string_3 = “00008-OK”; If($string_2 ”); If ($string_3”); If ($string_1 ”);
The output conclusion is:
007 is less than 00008 //Number comparison
00008-OK is less than 007 //String comparison
00008 is less than 00008-OK//String comparison produces conflicts
If possible, PHP will parameterize the string into numbers. When both sides of the comparison can be processed in this way, it will compare by numbers instead of letters. . PHP4 designers treat this as a feature, not a bug. From our point of view, if the string may be converted into a number during comparison, it is better to use the strcmp() function (please refer to Chapter 10).
Ternary Operator
A very useful structure is the ternary conditional operator, which plays a role between the Boolean operator and the "truth" branch structure. Its function is to have three operations. The value of the first operation is used to determine which of the other two operations is required. After evaluation, its value is returned. The syntax of the operator is as follows :
test-expression ?yes-expression:no-expression
If test-expression is true, the value of this operator is the result of yes-expression, otherwise, it is the result of no-expression.
For example, the following operation specifies $max_num as $first_num or $second_num, depending on which of the two parameters is larger:
$max_num = $first_num > $second_num ? $first_num:$second_num;
As we can see, the above description is equivalent to:
if ($first_num >$second_num )
$max_num = $first_num ;
else
$max_num = $second_num;
If the above example is used The ternary operator will be more concise.
Branch Structure
The two main structures of branches are if and switch.if is the most commonly used main branch choice, and it is usually the conditional structure that everyone learns first. Switch is also a good choice in some cases, such as when multiple possible branches are required based on a single value, or when a series of if statements are very cumbersome, it is very suitable to use switch.
if – else statement The syntax of
if is:
if(test)
statement-1
Or, it can also have an optional else branch:
if(test)
statement-1
else
statement-2
When the if statement is processed, the test operation will be evaluated , the result is interpreted as a Boolean value. If test is not true and there is no else clause, then the next statement after the if structure is executed.
Please note that the "statement" in the grammar can be a single statement ending with a semicolon, or it can be enclosed in braces A narrative block, or another conditional structure (which itself can be viewed as a single narrative). Conditions can be nested within each other to any depth. In addition, the Boolean operator can be a real Boolean value (that is, TRUE, FALSE, or the result of a Boolean operator or function), or any other type of value that can be interpreted as a Boolean value.
For complete information about Bollinger Value, please refer to Chapter 6. Simply put, the number "0", the string "0"" and the empty string """ are false, and all other values are true.
The following example outputs the absolute difference between two numbers, which demonstrates the use of nested nesting of conditions. It also mentions interpreting test results into Boolean values:
if ($first - $second)if ($first > $second){$difference = $first - $second;print(“The difference is $difference
”);}else{$difference = $second - $first;print( "The difference is $difference
");}elseprint("There is no difference
");
This code relies on the number "0" to be interpreted as a non-true value. If difference is "0", The test fails, and the output displays the "no difference" message. If there is a difference, a one-step test is performed (this example is deliberately made, because directly writing it like "$first != $second" is the same as the previous example. and easier to understand).
Additional else
At this moment, programmers who have used Pascal before may be aware that the else part is a bit strange. In other words, how does the else clause know which if it belongs to? The rules are actually very simple and are almost the same as in every other language except Pascal. Each else is matched with the closest one, of course first following the range restricted by the curly braces. If you want to ensure that the if statement remains independent and does not need to match else, you can enclose it in a pair of large arcs, as shown below:
if($num % 2 = =0)// $num Is it an even number? {if ($num > 2)print(“num is not prime
”); elseprint(“num is odd
”);
If $num is an even number greater than 2, the program code will print Print "num is not prime". If $num is an odd number, print "num is odd". If $num is exactly 2, nothing will be displayed.如果省略了大括弧,则else会附加到内层的if,因此如果$num等2,程式码也会错误地印出「num is odd」,如果$num的确是奇数,程式码则什么也不print.
In the examples in this chapter, we often use the remainder operator (%), which is explained in Chapter 12. For these examples, the reader only needs to know that "$x % $y" is "0" which means "$x is divisible by $y".
Elseif
It is very common to perform cascading type of testing, as shown in the following nested if statement:
if ($day == 5)print(“Five golden rings
"); elseif ($day ==4)print ("Four calling birds
"); elseif ($day ==3)print("Three French hens
"); elseif ($day ==2 )print("Tow turtledoves
"; elseif ($day ==1)print("A partridge in a pear tree
");
This type is very common, there is a special elseif structure to Deal with it. We can rewrite the previous example as:
if ($day == 5)print("Five golden rings
"); elseif($day == 4)print(" Four calling birds
"); elseif($day == 3)print("Three French hens
"); elseif($day == 2)print("Two turtledoves
"); elseif( $day ==1)print("A partridge in a pear tree
"); The
if, elseif... structure allows for sequential testing only when one branch test surface is successful. In theory, this is the same as. The previous example (a structure with five branches instead of a nested structure with five branches) is syntactically different, but the behavior is the same. Use whichever branch you think is better. And HTML Mode
You have learned from the previous chapters that you can freely use PHP tags to switch back and forth between HTML mode and PHP mode according to your needs. In any case, it is quite convenient if you need to include large areas in the page. block of HTML text, and there is no dynamic code or inserted variables, switch back to HTML mode and include it directly with text, which is simpler and more efficient than sending it with print or echo
What is less obvious is that this strategy works even within per se conditional structures. That is, you can use PHP to decide what HTML to send, and then "send" that HTML by temporarily switching back to HTML mode.
For example, the following code uses the print statement to construct a complete HTML web page (we assume a female() Boolean function to test it).