问题
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