1

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?

user2094178
  • 9,204
  • 10
  • 41
  • 70

2 Answers2

2

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

Petah
  • 45,477
  • 28
  • 157
  • 213
-1

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.

Community
  • 1
  • 1
David Harkness
  • 35,992
  • 10
  • 112
  • 134