2015-12-29 99 views
1

我得到這個代碼,得到了多少意見有在我的博客多「如果」條件

$pego_comment_caption = " Comments"; 

if (get_comments_number($post->ID) == 1) { 
    $pego_comment_caption = " Comment"; 
} 

的每一個職位由於我更多的是語法納粹的比我懂PHP的標題,「 0評論「實際上是不正確的,因爲0小於1並且..嗯,你知道

我想更改if條件,使其顯示單詞」評論「而不是」評論「,當有0或1評論。這可能很簡單,但我做不到。有人知道如何?

+7

一個真正的語法納粹會知道'0 Comments'實際上是正確的 –

+0

但是你根本不需要任何OR:'if(get_comments_number($ post-> ID)<= 1){' –

+0

Zero是其他的東西而不是某件事情,所以它需要複數。 (某些事物的分數在它們被表達爲「一半事物」或「三分之二事物」時也是單數形式,因此單數是合乎邏輯的,因爲你已經提到了'一件事',你會說'0.5事情',但)。 –

回答

4

只需向條件添加「或」。在PHP中,符號「或」布爾語句是||(而「和」,是&&

if (get_comments_number($post->ID) == 1 || get_comments_number($post->ID) == 0) { 
    $pego_comment_caption = " Comment"; 
} 

或者,你可以將它設置,使得任何低於1進入這一點,那麼你就必須如果(get_comments_number($ post-> ID)< = 1){ $ pego_comment_caption =「Comment」; }

或者,你可以使用in_array簡化此:

if (in_array(get_comments_number($post->ID), array(0, 1)) { 
    $pego_comment_caption = " Comment"; 
} 

這是當你有你測試了相同的變量(就像現在多個值,如果你想要說的還包括絕對有用2,你只需將它添加到陣列中的if語句,然後咣噹你設置。更少的代碼比其他。)

6

您可以使用三元操作符(?:)

只是檢查是否get_comments_number是大於1那麼這將是comments

嘗試這樣

$pego_comment_caption = (get_comments_number($post->ID) > 1 ? " Comments" : " Comment"); 

IDEONE

+0

我們可以在文字字符串中使用單引號:) '$ pego_comment_caption =(get_comments_number($ post-> ID)> 1?'Comments':'Comment'); – Ceeee

1

只是在你的語句來替換這個

if (get_comments_number($post - > ID) <= 1) { 
    $pego_comment_caption = " Comment"; 
}