PHP : ternary operator

2020-05-06 01:59发布

问题:

This seems like a very simple question but everything I try, gives me an error.

    if ( $query_results->have_posts() ) :   
    $count_results = $query_results->found_posts;

Question: How to add else statement/functionality to this code?

I've tried to add parentheses & else, I've also tried all combinations with : and ?. Nothing works..

回答1:

That's not a ternary operator; it's an uncommon if block syntax. Try this:

if ( $query_results->have_posts() ) {
    $count_results = $query_results->found_posts;
} else {
    // whatever
}

Note: there will be an endif; later in your code, which you also need to replace using the above syntax. There may also be elseif (...): or else : statements. While these are acceptable and work, they are generally considered more difficult to read, and you are better off using braces, as in my example above.

For what it's worth, the only project I have ever seen use the colon syntax (if (...):) is Wordpress. I'm sure they had a reason for doing so, but it's definitely the less common syntax.



回答2:

You're not using the ternary operator correctly. Try:

$count_results = ($query_results->have_posts())? $query_results->found_posts : "YOUR ELSE EXPRESSION" ;


标签: php wordpress