2012-11-26 38 views
0

我怎麼能把這個if語句變成一個三元語句?三元聲明不按預期測試值

if (!empty($vendor_address_row['address2'])){ 
    $address_obj['address2'] = $vendor_address_row['address2']; 
    }else{ 
    $address_obj['address2'] = '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>';  
    } 

我有特里

$vendor_address_row['address2'] ? $address_obj['address2'] = '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>' : $address_obj['address2'] = '';

!empty($vendor_address_row['address2']) ? $address_obj['address2'] = '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>' : $address_obj['address2'] = '';

既不工作。除此之外,可能還有更簡單的方法。非常感謝你。

+0

我可以說,你的標題(「_ternary語句沒有正確測試值」)是不正確的:那個測試不正確的不是你的聲明。你沒有使用比較,但是賦值和賦值在新值爲真時給出真實值。 – Tadeck

回答

1

這取決於是否$vendor_address_row['address2']總是被定義或不。

如果是(和版本> = 5.3):

$address_obj['address2'] = $vendor_address_row['address2'] ?: '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>'; 

或(<版本5.3):

$address_obj['address2'] = $vendor_address_row['address2'] ? $vendor_address_row['address2'] : '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>'; 

它是不是:

$address_obj['address2'] = !empty($vendor_address_row['address2']) ? $vendor_address_row['address2'] : '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>'; 

你如果需要的話可以反轉操作數以擺脫!empty()

0

這應該是:

echo $address_obj['address2'] = !empty($vendor_address_row['address2']) ? $vendor_address_row['address2'] : ('<tr><td colspan="1">'.$address_row['address2'].'</td></tr>'); 

或將其保存到一個變量:

$address_obj['address2'] = !empty($vendor_address_row['address2']) ? $vendor_address_row['address2'] : ('<tr><td colspan="1">'.$address_row['address2'].'</td></tr>'); 
0

應該

$address_obj['address2'] = empty($vendor_address_row['address2']) ? '<tr><td colspan="1">'.$address_row['address2'].'</td></tr>' : $vendor_address_row['address2'] ; 
+0

謝謝你。我對它的工作方式感到有點困惑。如果它的'empty()'測試的結果爲false,那它怎麼會不執行冒號右側的任務呢?我認爲應該在'empty()'測試的值爲true時完成。 – 1252748

+0

在':'之後,你將它設置爲$ vendor_address_row ['address2']而不是一個空字符串。你爲什麼走這條路?再次感謝。 – 1252748

+0

問題是「我怎麼能把這個if語句變成一個三元語句?」我所做的只是跟隨你的語句的控制。在if語句中沒有空字符串被設置 – Baba