-3

My intention is to find a short version of:

$x ? $x : $y

where $x gets evaluated only once.

WeSee
  • 3,158
  • 2
  • 30
  • 58
  • 5
    This question appears to be off-topic because OP can test it themselves. – Kermit Feb 10 '14 at 21:29
  • possible duplicate of [?: operator PHP](http://stackoverflow.com/questions/1993409/operator-php) or http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php – Bergi Feb 10 '14 at 21:34
  • valid (assuming `$x` is defined (and same for `$y` if `$x` is falsey)), but pointless. It's a no-op. Are you thinking of doing something like `$x = $x?: $y;`? – traq Feb 10 '14 at 21:54

2 Answers2

2

From the PHP manual entry on Comparison Operators :

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

So, you'll need to be using PHP 5.3 or greater to get this "shortcut" feature. Although, why you'd want a shortcut for an operator that already is a shortcut is another question...

Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74
  • Maybe for actions like these: `$val = findById($id) ?: createWithId($id);` ? It's a stupid approach, but PHP isn't that logical imho (comparing with other languages, that is). – Diamondo25 Feb 10 '14 at 21:32
0

Yes, it is valid.

You know, you could have just tried it. :)

http://3v4l.org/68Zrf

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308