具有多个条件的三元运算符 [英] Ternary operator with multiple conditions

查看:128
本文介绍了具有多个条件的三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试正确设置三元运算符的格式以在php中使用多个条件:

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

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

问题是在这种格式下,即使$ var是1或2,我也总是不正确.以一个条件为例,例如 $ var == 0 ,它可以正常工作.任何帮助都将受到欢迎.

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.

推荐答案

此语句将始终 true :

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

因为 $ var 不能同时是两个值,所以它总是 not 至少是两个值之一.满足 ||| 运算符.

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

如果您想知道 $ var 是否为两个值之一:

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

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

如果您想知道 $ var 是否不是两个值中的 ,则可以取反条件:

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.

这篇关于具有多个条件的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆