PHP : ternary operator

2020-05-06 01:46发布

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..

标签: php wordpress
2条回答
我只想做你的唯一
2楼-- · 2020-05-06 02:10

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

$count_results = ($query_results->have_posts())? $query_results->found_posts : "YOUR ELSE EXPRESSION" ;
查看更多
冷血范
3楼-- · 2020-05-06 02:13

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.

查看更多
登录 后发表回答