具有多种条件的三元运算符
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.
您好我正在尝试正确格式化三元运算符以在php中使用多个条件: p> \ n
$ result =($ var!== 1 || $ var!== 2)? '':'default';
code> pre>
问题是,在这种格式中,即使iv $ var为1或2,我也总是不正确。 示例 $ var == 0 code>它工作正常。 欢迎任何帮助。 p>
div>
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.
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';