2013-02-15 292 views
7

使用?:条件运算符与||逻辑OR之间有什么区别。有什么区别? :和||

我发现,我的代码使用:

$screenpixelratio = !empty($_COOKIE['screenpixelratio']) || $_COOKIE['screenpixelratio'] || $fallback_pixelratio; 

但不是:

$screenpixelratio = !empty($_COOKIE['screenpixelratio']) ? $_COOKIE['screenpixelratio'] : $fallback_pixelratio; 

可能有人请解释为什么它会以一个工作,而不是其他。

+1

一(称为三元运算符)是一个简化的等效 “如果测试”;另一个是逻辑“或” - 非常重要的区别,做完全不同的事情 – 2013-02-15 15:29:23

+0

第二个例子是一个三元运算符。第一个将它遇到的第一个真值赋给'$ screenpixelration'。 – BenM 2013-02-15 15:29:28

+0

三元运营商 – 2013-02-15 15:31:06

回答

8

||二元运算符是一个有两个参数

为应对运营商它说它会先检查它是否真的不会再进一步​​检查其他检查

?:三元运算符是一个接受三个参数的运算符。参数和结果可以是不同的类型。

Expression1 ? Expression2 : Expression3; 

enter image description here

18

第(conditional or)是说......

this or this or this 

其他(ternary operation)是说

if this then this otherwise that 
+0

清晰简洁 – 2013-02-15 15:31:15