PHP in the ternary operator is also called the three-mesh operator, in fact, I often call it a question mark run-in can actually do this, ternary operators can achieve a simple conditional judgment function, I would like to introduce some examples of ternary operators
The function of the ternary operator is consistent with the "if....else" process statement, which is written in one line, the code is refined, and the execution efficiency is high. Using the ternary operator properly 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 true, the statement "EXPR2" is executed, otherwise "EXPR3" is executed.
<? php$a=10; $b =20; $c = $a > $b? ($a-$b):($a + $b);//Description: If the variable A is greater than variable B executes after the question mark, otherwise execute: Echo $c after the colon;? >
Expressions can be functions, arrays, and so on.
In fact, the ternary operator can be extended to use, when the conditions set or not, the execution of the statement can be more than one sentence, sample the following format:
(EXPR1)? (EXPR2). (EXPR3): (EXPR4). (EXPR5);
It is clear to us that multiple execution statements can be used with a string operation symbol ("."). ), each execution statement is surrounded by small angle brackets to indicate that it is an independent and complete execution statement. This expands its functionality closer to the "if...else" process statement.
The ternary operator can also be used in a nested set. For example, a greater than B is established: If A is less than C, then x=c-a otherwise x=a-c; otherwise a less than B is established: 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 in nesting are not very readable, and the maintenance of the code is likely to be problematic in the future, so let's just use if else if to implement it.
Thank you for reading, hope to help everyone, thank you for the support of this site!
The above is the whole content of this article, I hope that everyone's study has helped.