Multiple "if" conditions

I got this code that gets a caption for how many comments there are in each post of my blog

$pego_comment_caption = " Comments";

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

Since I'm more of a grammar nazi than I understand PHP, "0 Comments" is actually gramatically incorrect since 0 is less than 1 and.. well, you know

I'd like to change the if conditions making it display the word "Comment" instead of "Comments" when there are 0 OR 1 comment. It's probably simple but I couldn't do it. Does anybody know how to?

Upvotes: 0

Views: 128

Answers (3)

user2963176
user2963176

Reputation: 74

Just replace this in your statement

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

Upvotes: 1

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

You can use Ternary operator (?:)

Just check if get_comments_number is greater then 1 then it'll be comments

Try like this

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

IDEONE

Upvotes: 6

MasterOdin
MasterOdin

Reputation: 7886

Just add an "or" to the conditional. In PHP, the symbol for "or" in boolean statements is || (while "and" is &&)

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

Alternatively, you could set it such that anything less than 1 goes into this, then you'd have: if (get_comments_number($post->ID) <= 1) { $pego_comment_caption = " Comment"; }

Alternatively, you could use in_array to simplify this:

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

This is definitely useful when you have multiple values you're testing the same variable for (as now if you wanted to say also include 2, you would just add it to the array in the if statement and bam you're set. Less code than the alternative.)

Upvotes: 4

Related Questions