2010-11-02 195 views
0

可能重複:
the code 「 : 」 in php':'和'?'的含義

我經常看到使用大量的PHP代碼?,但我實際上並不明白它的用途。這裏的一個例子:

$selected = ($key == $config['default_currency']) ? ' selected="selected"' : ''; 

有人可以請我清理嗎? :)

+2

http://php.net/manual/language.operators.comparison.php#language.operators.comparison.ternary – poke 2010-11-02 21:45:53

+1

*(相關)* [這個符號在PHP中的含義是什麼](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) – Gordon 2010-11-27 00:41:37

回答

14

這是三元運算符。它基本上是一條線上的if/else。

例如,那些線:

if (!empty($_POST['value'])) { 
    $value = $_POST['value']; 
} else { 
    $value = ""; 
} 

可以通過這條線被縮短:

$value = (!empty($_POST['value'])) ? $_POST['value'] : ""; 

它可以使代碼更易於閱讀,如果你不濫用它

+0

+1對**如果你不濫用它**。我見過很多嵌套三元條件的實例,每次都想讓我哭泣。 – netcoder 2010-11-02 21:48:56

+0

+1 **如果你不濫用它**。 (爲了一切美好的事情,不要住宿!) – drudge 2010-11-02 21:49:26

2

這是簡寫的if語句

你可以把這種說法變成這樣:

if ($key == $config['default_currency']) { 
    $selected = ' selected="selected"'; 
} else { 
    $selected = ''; 
} 
2

這是ternary conditional operator,就像在C.

您的代碼相當於:

if ($key == $config['default_currency']) 
{ 
    $selected = ' selected="selected"'; 
} 
else 
{ 
    $selected = ''; 
} 
0

在僞代碼中,

variable = (condition) ? statement1 : statement2 

映射到

if (condition is true) 
then 
variable = statement1 
else 
variable = statement2 
end if