Shortest if/else using ternary operators

I have this piece of code:

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

I was under the impression I could do like:

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

But when $options["placeholder"] is not empty then it returns 1, as it is a ternary operator.

Do I have to always issue the variable 2 times?


If you can be sure that $options['placeholder'] will be set--if not you can prefix it with @ to suppress the warning--you can drop the empty call:

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

The Elvis operator ?: evaluates to the left hand side if it is truthy ( true when coerced to a boolean value such as 1 or a non-empty string 'foo' ) or the right hand side if not.


Yes. There is however been many requests wanting to change this:

  • https://wiki.php.net/rfc/ifsetor
  • https://wiki.php.net/rfc/isset-set-operator
  • 链接地址: http://www.djcxy.com/p/57732.html

    上一篇: JavaScript“或”

    下一篇: 最短的if / else使用三元运算符