多个“如果”条件

问题描述 投票:1回答:3

我得到了这个代码,其中包含我博客每篇文章中有多少条评论的标题

$pego_comment_caption = " Comments";

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

由于我更像是一个语法纳粹语,而不是我理解PHP,“0评论”实际上是非常不正确的,因为0小于1并且......嗯,你知道

我想改变if条件,当有0或1评论时,它显示“评论”而不是“评论”。它可能很简单,但我无法做到。有谁知道怎么做?

php if-statement
3个回答
6
投票

您可以使用三元运算符(?:)

只要检查get_comments_number是否大于1然后它将是comments

试试这样吧

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

IDEONE


4
投票

只需在条件中添加“或”即可。在PHP中,布尔语句中“或”的符号是||(而“和”是&&

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

或者,你可以设置它使得任何小于1的东西进入这个,然后你有:if(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语句中的数组中,并将bam设置为你。比另类。)


1
投票

只需在您的陈述中替换它

if (get_comments_number($post - > ID) <= 1) {
    $pego_comment_caption = " Comment";
}
© www.soinside.com 2019 - 2024. All rights reserved.