In PHP, the ternary operator is used to select and execute one of the other two expressions based on the result of the first expression, the syntax "(expr1)?(expr2):(expr3); "; If the first expression "expr1" is true, the second expression "expr2" is executed, otherwise the "expr3" expression is executed.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In PHP, ternary arithmetic The operator can implement a simple conditional judgment function, that is, select one of the other two expressions and execute it based on the result of the first expression. The ternary operator is also called the ternary operator or the conditional operator.
The function of the ternary operator is consistent with the "if else" statement. It can be written in one line, making the code concise and more efficient. Proper use of the ternary operator in PHP programs can make scripts more concise and efficient.
The syntax format of the ternary operator is as follows:
(expr1)?(expr2):(expr3); //表达式1?表达式2:表达式3
If the condition "expr1" is true, execute the statement "expr2", otherwise execute "expr3".
The sample code is as follows:
The running results are as follows:
$a 是偶数!
In addition, expr2 and expr3 can also be omitted using single quotes ('') or double quotes ("") Any one of them, to avoid unnecessary code, as shown below:
' : ""; $b % 2 == 0 ? '' : print '$b 是奇数!'; ?>
The running result is as follows:
$a 是偶数! $b 是奇数!
Note: When using the ternary operator, if you need to print a string, it is recommended Use print statements instead of echo statements.
Not only that, the ternary operator can also be used in an extended manner. When the set conditions are true or not, the execution statement can be more than one sentence. The syntax format is as follows:
(expr1) ? (expr2).(expr3) : (expr4).(expr5);
As you can see, multiple Execution statements can be connected using the string operator ".", and each execution statement is wrapped in parentheses to indicate that it is an independent and complete execution statement.
At the same time, the ternary operator can also be used nested. The example is as follows:
$b ? ($a<$c ? $c-$a : $a-$c) : ($b<$c ? $c-$b : $b-$c); echo '$x ='.$x; ?>
Note that the assignment operation in the fifth line will wait for the ternary operator to be executed before it is executed.
The running results are as follows:
$x =2
Although the nested ternary operator can save a lot of code, its readability is not very good, and it is also very inconvenient to maintain the code in the future, so like In this case, we try to use if else statements to achieve this.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to use the ternary operator in php. For more information, please follow other related articles on the PHP Chinese website!