2013-02-15 286 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