Php ternary operator instance details, operator instance details
The functions of the ternary operator are the same as those of the "if... else" flow statement. It is written in one line, and the code is refined and the execution efficiency is high. The proper use of ternary operators in PHP programs makes scripts 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 ".
<? PHP $ a = 10; $ B = 20; $ c = $ a> $ B? ($ A-$ B) :( $ a + $ B); // Note: If variable a is greater than variable B, execute the following question mark; otherwise, execute: echo $ c;?>
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 (". ), and each execution statement is enclosed by small angle brackets to indicate that it is an independent and complete execution statement. In this way, its function is closer to the "if... else" flow statement.
The ternary operators can also be nested. For example, when a is greater than B, if a is less than c, then x = c-a; otherwise, x = a-c; otherwise, 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 for implementation.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!