3

In an online tutorial I have seen the following snippet of code:

$this->data = $data ?: \Input::all();

Is this a standard ternary operator? What would happen when $data evaluates to true?

Does the following code do the same thing as the original I posted?

$this->data = $data ? null : \Input::all();
toro2k
  • 19,020
  • 7
  • 64
  • 71
Gravy
  • 12,264
  • 26
  • 124
  • 193
  • possible duplicate of [Reference - What does this symbol mean in PHP?](http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php) and all these http://stackoverflow.com/search?q=%5Bphp%5D+body%3Aternary+is%3Aquestion – Mike B Oct 16 '13 at 11:49
  • @MikeB - Wasn't a duplicate question. toro2k edited my question so now it has become a duplicate of another. – Gravy Oct 16 '13 at 12:19

1 Answers1

8

It's a ternary operator, shortcut of

 $this->data = $data? $data : \Input::all();

From http://php.net/manual/en/language.operators.comparison.php

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.

Community
  • 1
  • 1
Luca Rainone
  • 16,138
  • 2
  • 38
  • 52
  • 1
    Aaah... Thanks. Not seen it done like that before, but very useful to know. I will accept your answer as soon as it lets me. – Gravy Oct 16 '13 at 10:31
  • It's less commonly used because (1) relatively new so many devs don't know it, (2) can't use it if you want your code to work with PHP 5.2, (3) can't be used for common examples like `isset($x) ? $x : ''`, as you'd just get the boolean returned by `isset()`. – Spudley Oct 16 '13 at 11:35
  • I generally use it when I should return some data from database. In this case the key of the array (generally) always exists but it can be an empty string. – Luca Rainone Oct 16 '13 at 11:42