In php, the ternary operator is also called the three-object operator. In fact, I often call it the question mark operator to do this. the ternary operator can implement simple conditional judgment, next I will introduce some examples of ternary operators. functions of ternary operators and ldquo ;... in php, the ternary operator is also called the three-object operator. In fact, I often call it the question mark operator to do this. the ternary operator can implement simple conditional judgment, next I will introduce some examples of ternary operators.
Functions of ternary operators and "if .... the else process statements are the same. they are written in one line, with refined code and high execution efficiency. the proper use of the ternary operators in the PHP program makes the script more concise and efficient, the code syntax is as follows:
(Expr1 )? (Expr2) :( expr3); // expression 1? Expression 2: Expression 3
Explanation:If the condition "expr1" is true, execute the statement "expr2"; otherwise, execute "expr3". the code is as follows:
$ B? ($ A-$ B) :( $ a + $ B); // Note: If variable a is greater than variable B, execute the following question mark; otherwise, execute: echo $ c;
The expressions can be functions, arrays, and so on.
In fact, the ternary operators can be extended and used. when the set conditions are true or not true, more than one statement can be executed, in the following format:
(Expr1 )? (Expr2). (expr3): (expr4). (expr5 );
We can see that multiple execution statements can use the string operator number (".) join, each execution statement is surrounded by small angle brackets to indicate that it is an independent and complete execution statement, so that its function is closer to "if... else flow statement.
At the same time, the ternary operators can also be nested. for example, when a is greater than B, if a is less than c, x = c-a; otherwise, x = a-c; otherwise, when a is less than B, if B is less than c, then x = c-B; otherwise, x = B-c:
$ A> $ B? $ X = ($ a <$ c? $ C-$ a: $ a-$ c): $ x = ($ B <$ c? $ C-$ B: $ B-$ c );
The ternary operators used for nesting are not very readable, and there may be problems with code maintenance in the future. so in this case, we should directly use if else if to implement it.
Tutorial link:
Reprint at will ~ However, please keep the tutorial address★