2015-12-29 77 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"; 
}