使用三元运算符的最短if/else


Shortest if/else using ternary operators

我有一段代码:

<?=!empty($options["placeholder"]) ? $options["placeholder"]:'search...'?>

我当时的印象是我可以做的事情:

<?=!empty($options["placeholder"]) ?:'search...'?>

但当$options["placeholder"]不为空时,它返回1,因为它是一个三元运算符。

我必须总是发布变量2次吗?

是。然而,有许多请求想要改变这一点:

  • https://wiki.php.net/rfc/ifsetor
  • https://wiki.php.net/rfc/isset-set-operator

如果您可以确定$options['placeholder']将被设置——如果不能,您可以在它前面加上@来抑制警告——您可以放弃empty调用:

<?= $options["placeholder"] ?: 'search...' ?>

Elvis运算符?:truthy(当被强制为boolean值(例如1或非空字符串'foo')时为true)的情况下评估为左手侧,或者在不为的情况下为右手侧。