3

In PHP, is there a more concise way of writing $x ? $x : $y? Repeating $x feels unnecessary, especially if it's a longer expression. It's not very important how false values are handled, as long as $y is returned when $x is undefined or null.

In Perl, I'd use $x // $y or $x || $y.

Tim
  • 13,904
  • 10
  • 69
  • 101
  • try this link: http://stackoverflow.com/questions/6911235/is-there-a-better-way-of-writing-v-v-0-1-0 it is javascript but works perfectly with PHP, hope it helps –  Jan 11 '12 at 13:58
  • @Gerep: The only similarity between the questions seems to be the operator. – Tim Jan 11 '12 at 14:04

1 Answers1

9

Yes, but only if you have PHP 5.3+ installed. You can simply miss out the middle part:

$x ?: $y

See the documentation in the manual for comparison operators.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • 3
    Note that it isn't _actually_ "miss[ing] out the middle part" so much as it is the use of a different operator. – Lightness Races in Orbit Jan 11 '12 at 13:58
  • 1
    @lonesomeday: The manual has _all sorts_ of confusing and misleading phrasing. For example the continual use of the term "ternary operator" on the page about conditional operators, propagating a horrid myth. Fortunately, PHP devs accept manual bug reports and usually act on them swiftly; I've submitted more than a few myself that have been promptly adopted. – Lightness Races in Orbit Jan 11 '12 at 14:03
  • 1
    Calling this a "ternary operator" is _even worse_ than doing so for `a?b:c`, not least because it's a _binary_ operator. – Lightness Races in Orbit Jan 11 '12 at 14:03
  • It's arguably a ternary operator with the second argument implicit. Clearly you have strong opinions on the matter. – lonesomeday Jan 11 '12 at 14:05
  • 1
    By that logic, every unary operator is _actually_ a ternary operator with two implicit dummy operands. You'll get no traction with that. – Lightness Races in Orbit Jan 11 '12 at 14:06