1

When the shorthand syntax used in the scenario, I'm trying to use it but its giving me some weird results

($value == 'yes' ?: 'Show Text');

Thanks

Stanley Ngumo
  • 4,089
  • 8
  • 44
  • 64

1 Answers1

8

It's the binary conditional operator introduced in PHP 5.3. PHP's conditional operator is traditionally a ternary operator (accepting three operands), but the binary (accepting two operands) form was added, making the operand between the ? and : optional:

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 in your example, if $value is 'yes', the result is TRUE (1) because the result is the first expression's value ($value == 'yes'). If $value is not 'yes', the result is 'Show Text'.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • 1
    Also known as the elvis operator https://en.wikipedia.org/wiki/Elvis_operator – Sam Dufel Jun 25 '16 at 14:53
  • @SamDufel: Ah! And "doh" on the article, of course, in this form the conditional operator *isn't* a ternary operator, it's a binary operator. Cool. – T.J. Crowder Jun 25 '16 at 14:58