This article mainly introduces the detailed introduction to the implementation of ternary operator in PHP. It has certain reference value. Now I share it with you. Friends in need can refer to
Ternary operator in PHP. It is also called the ternary operator. In fact, I often call it the question mark operator. In fact, it can be done like this. The ternary operator can implement simple conditional judgment functions. Now let me introduce to you some ternary operators. Example
The function of the ternary operator is consistent with the "if...else" process statement. It is written in one line, with concise code and high execution efficiency. Proper use of the ternary operator in PHP programs can make scripts more concise and efficient. The syntax of the code is as follows:
(expr1)?(expr2):(expr3); //表达式1?表达式2:表达式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); //说明:如果变量a大于变量b则执行问号后面的,否则就执行:冒号后面的 echo $c; ?>
Expressions can be functions, arrays, etc.
In fact, the ternary operator can be extended and used. When the set condition is true or not, the execution statement can be more than one sentence. Try the following format:
(expr1) ? (expr2).(expr3) : (expr4).(expr5);
We can clearly see that multiple execution statements can be connected using string operators ("."), and each execution statement is surrounded by small angle brackets to indicate that it is an independent and complete execution statement. . After this expansion, its function is closer to the "if...else" process statement.
At the same time, the ternary operator can also be used nested. For example, when a is greater than b: if a is less than c, then 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 readability of the nested ternary operator is not very good, and there may be problems with maintaining the code in the future, so in this case we still use if else if directly. Make it happen.
Related recommendations:
Detailed explanation of php ternary operator and if
Knowledge points about php ternary operator Summary
The above is the detailed content of Detailed introduction to php ternary operator examples. For more information, please follow other related articles on the PHP Chinese website!