2015-11-04 111 views
0

首先,我是PHP的新手。php檢查兩個變量是否爲空並將它們合併到一起

我想檢查兩個變量是否都是空的,如果是這樣,合併它們togheter只顯示一個結果,但如果其中一個不是空的,比我必須顯示的是值。

我目前有:

$customerNotesWC = ""; 
$DYSPrintableOrderNotes = "test note"; 

這裏是我試過至今代碼:

function displayCustomerOrderNotes($customerNotesWC,$DYSPrintableOrderNotes){ 
    if ($customerNotesWC == "") { 
     $customerNotesWC = "(none)"; 
    } 
    if ($DYSPrintableOrderNotes ==""){ 
     $DYSPrintableOrderNotes = "(none)"; 
    } 
    if ($DYSPrintableOrderNotes == "(none)" && $customerNotesWC == "(none)"){ 
     $NotesToDisplay = "(none)"; 
    } 
    else { 
     $NotesToDisplay = $customerNotesWC . "<br/>" . $DYSPrintableOrderNotes; 
    } 
} 

不幸的是,這並不工作,因爲結果是:

(none)  
Pre-sale order note 

我知道必須有更好的方法來實現這一點,任何建議將非常感激。 非常感謝

回答

2

爲了讓你所希望的功能只在兩個值都是空白時纔打印「(none)」,修正你的代碼最簡單的辦法就是刪除將任一值設置爲「(none )「,並更改您的主要if語句來檢查」「:

function displayCustomerOrderNotes($customerNotesWC,$DYSPrintableOrderNotes){ 
    if ($DYSPrintableOrderNotes == "" && $customerNotesWC == ""){ 
     $NotesToDisplay = "(none)"; 
    } 
    else { 
     $NotesToDisplay = $customerNotesWC . "<br/>" . $DYSPrintableOrderNotes; 
    } 
    //shouldn't there be an echo $NotesToDisplay; or return $NotesToDisplay; ? or something? 
} 
+0

我剛試過你的答案,但它仍然打印」(無)「。目前我有$ customerNotesWC空白和$ DYSPrintableOrderNotes不爲空。 – Nick

+0

Ctrl Shift F5,它應該可以工作 – 2015-11-04 16:20:14

+0

好的抱歉,我的錯誤是我在代碼中沒有注意到的錯誤。只需修復它,它現在可以完美運行。非常感謝 – Nick