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
  • 8,696
  • 10
  • 40
  • 66

2 Answers2

2

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

Petah
  • 44,167
  • 27
  • 153
  • 209
-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
  • 34,910
  • 10
  • 110
  • 128