The ternary operator's functionality is consistent with the "if....else" process statement, which is written in a single line, with a streamlined code and high execution efficiency. Using the ternary operator appropriately in a PHP program can make the script more concise and efficient. The syntax for the code is as follows:
(EXPR1)? (EXPR2):(EXPR3); Expression 1-expression 2: Expression 3
Explanation: If the condition "EXPR1" is established, the statement "EXPR2" is executed, otherwise "EXPR3" is executed.
| The code is as follows |
Copy Code |
? Php $a = 10; $b = 20; $c = $a > $b? ($a-$b):($a + $b); Note: If variable A is greater than variable B, the following question is executed, otherwise it is executed: after the colon Echo $c; ?> |
An expression can be a function, an array, and so on.
In fact, the ternary operator can be extended to use, when the set of conditions or not set up, execute the statement can be more than one sentence, the following format:
| The code is as follows |
Copy Code |
(EXPR1)? (EXPR2). (EXPR3): (EXPR4). (EXPR5); |
We see very clearly that multiple execution statements can use the string operator notation ("." , each execution statement is surrounded by small brackets to indicate that it is an independent and complete execution statement. This extends its functionality to a more approximate "if...else" process statement.
The ternary operator can also be used in nested nesting. For example, A is larger 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:
| The code is as follows |
Copy Code |
$a > $b? $x = ($a < $c? $c-$a: $a-$c): $x = ($b < $c? $c-$b: $b-$c); |
The ternary operators used in nesting are not very readable, and future maintenance of the code is likely to be problematic, so let's do it directly using if else if.