PHP:三元运算符 [英] PHP : ternary operator

查看:54
本文介绍了PHP:三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这似乎是一个非常简单的问题,但我尝试的所有方法都会出错.

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;

问题:如何向此代码添加 else 语句/功能?

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

我尝试添加括号 &else,我也尝试了所有与 :? 的组合.什么都不起作用..

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

推荐答案

那不是三元运算符;这是一种不常见的if块语法.试试这个:

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
}

注意:您的代码后面会有一个 endif; ,您还需要使用上述语法替换它.也可能有 elseif (...):else : 语句.虽然这些是可以接受的并且有效,但它们通常被认为更难阅读,你最好使用大括号,就像我上面的例子一样.

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.

就其价值而言,我见过的唯一一个使用冒号语法(if (...):)的项目是 Wordpress.我相信他们这样做是有原因的,但这绝对是不太常见的语法.

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.

这篇关于PHP:三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆