Ternary operator with multiple conditions

自古美人都是妖i 提交于 2020-01-17 05:47:29

问题


Hello I am trying to properly format ternary operator to be using multiple conditions in php:

$result = ($var !== 1 || $var !== 2) ? '' : 'default';

The problem is that in this format I always get not true even iv the $var is 1 or 2. With one condition for example $var == 0 it is working fine. Any help will be welcome.


回答1:


This statement will always be true:

($var !== 1 || $var !== 2)

Because $var can never simultaneously be both values, it will always not be at least one of the two values. Which satisfies the || operator.

If you want to know whether $var is one of the two values:

($var === 1 || $var === 2)

If you want to know if $var is neither of the two values, you can negate the condition:

(!($var === 1 || $var === 2))

Or individually negate the operators in the condition and use && instead of || (since all conditions need to be met to prove the negative, instead of just one condition to prove the positive):

($var !== 1 && $var !== 2)

Depending on readability and personal preference.




回答2:


If $var is 0 , $result is "default" but 1 and 2 enter in condition, both are different from both and always enter.

$result = ($var !== 1 && $var !== 2) ? '' : 'default';


来源:https://stackoverflow.com/questions/38128632/ternary-operator-with-multiple-conditions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!