dqed19166 2009-10-01 21:13
浏览 99
已采纳

如何在PHP中使用三元运算符(?:)作为“if / else”的简写?

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

Working code using if statement:

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 />';

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 />';
  • 写回答

11条回答 默认 最新

  • duanan2732 2009-10-01 21:30
    关注

    The

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

    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 */
    }
    

    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'];
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(10条)

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏