如何替换“如果"带有三元运算符 (?:) 的语句? [英] How to replace "if" statement with a ternary operator ( ? : )?
问题描述
基于本页的示例,我想转换以下内容if
语句到三元运算符.
Based on the examples from this page, I wanted to convert the below if
statement to a ternary operator.
使用if
语句的工作代码:
if (!empty($address['street2'])) echo $address['street2'].'<br />';
我不确定应该如何使用三元运算符编写它,以便 echo
仅在 street2
存在于数组中并且不是空字符串时才起作用.
I am not sure how this should be written using a ternary operator so that the echo
works only if street2
exists in the array and is not an empty string.
推荐答案
(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.
这篇关于如何替换“如果"带有三元运算符 (?:) 的语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!