2011-08-15 53 views
0

如果我下面如何設置這種情況下,取決於是否規則

$x = "go"; 
$y = "went"; 
$z "gone"; 

,我需要設置標題,其中標題是

$title = $x;    //only if "y" empty no care about "z" if empty or not 
$title = $x . " - " . $y; // if "y" not empty and "z" is empty 
$title = $y . " - " . $z; // if "z" not empty and "y" not empty 

這是我的嘗試,但外地和/或看起來很透氣(我是noob)

$empty = ""; // i've creaty empty example 
$x = "go"; 
$y = "went"; 
$z "gone"; 

if ($y==$empty) { 
$title = $x; // output should be go 

} else if($y!=$empty && $z==$empty) { 
$title = $x . " - " . $y; // output should be go - went 

} else if($y!=$empty && $z!=$empty) { 
$title = $y . " - " . $z; // output should be went - gone 

} else { 
$title = $x; // output should be go 
} 

有沒有人有更好的建議!非常感謝

+0

瞭解如何使用三元條件。 – Layke

+0

第一個條件是一樣的,所以你可以刪除第一個 – wonk0

回答

1
$title = empty($y) ? $x : (empty($z) ? $x."-".$y : $y."-".$z); 
+0

這不會通過代碼審查在這裏,這種說法是非常難以理解/不可維護 – wonk0

+0

我認爲與兩個層次的嵌套可以處理這個 – rabudde

+0

好吧,我改變它「不太可讀/可維護」;) – wonk0