如何在PHP中使用三元运算符(?:)作为"if/else"的简写? [英] How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

查看:69
本文介绍了如何在PHP中使用三元运算符(?:)作为"if/else"的简写?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据此页面上的示例 ,我可以使用下面的工作代码示例.

Based on the examples from this page, I have the working and non-working code samples below.

使用if语句的工作代码:

if (!empty($address['street2'])) echo $address['street2'].'<br />';

使用三元运算符的非工作代码:

Non-working code using ternary operator:

$test = (empty($address['street2'])) ? 'Yes <br />' : 'No <br />';

// Also tested this
(empty($address['street2'])) ? 'Yes <br />' : 'No <br />';

更新
在Brian提出技巧之后,我发现回显$test输出预期的结果.下面的作品就像一个魅力!

UPDATE
After Brian's tip, I found that echoing $test outputs the expected result. The following works like a charm!

echo (empty($storeData['street2'])) ? 'Yes <br />' : 'No <br />';

推荐答案

The

(condition) ? /* value to return if condition is true */ 
            : /* value to return if condition is false */ ;

语法不是"if的简写"运算符(?称为条件运算符),因为您无法以与执行以下操作相同的方式执行代码:

syntax is not a "shorthand if" operator (the ? is called the conditional operator) because you cannot execute code in the same manner as if you did:

if (condition) {
    /* condition is true, do something like echo */
}
else {
    /* condition is false, do something else */
}

在您的示例中,当$address不为空时,您正在执行echo语句.对于条件运算符,您不能以相同的方式进行操作.但是,您可以做的是echo条件运算符的结果:

In your example, you are executing the echo statement when the $address is not empty. You can't do this the same way with the conditional operator. What you can do however, is echo the result of the conditional operator:

echo empty($address['street2']) ? "Street2 is empty!" : $address['street2'];

,这将显示街道为空!"如果为空,则将显示street2地址.

and this will display "Street is empty!" if it is empty, otherwise it will display the street2 address.

这篇关于如何在PHP中使用三元运算符(?:)作为"if/else"的简写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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