1

This is not exactly a "problem", but more a "why" question.

Based on the following example:

echo 'test' . ( true ?  : 'some-test' );

Why is the result of this: test1 instead of what one might expect: test.

Or in other words: Why is an empty return statement 1 (or actually true) instead of null ?

Damien Overeem
  • 4,399
  • 4
  • 31
  • 53

4 Answers4

8

As of PHP 5.3, the middle part of the ternary ?: operator can be omitted.
foo ?: bar is equivalent to foo ? foo : bar. So true ?: ... always returns the first true.

foo ? : bar with the meaning of "nothing if true" is and was always invalid, since this expression has to return something, it can't just return nothing. If anything, you'd want this: foo ? null : bar.

deceze
  • 471,072
  • 76
  • 664
  • 811
  • Interesting, so `?` and `:` are still treated as two separate tokens and the parser just checks if there is an expression at all between them regardless of whitespace? I guess that's how it retains the title "ternary operator" while appearing to accept two expressions at the very least. – BoltClock Apr 28 '14 at 13:15
  • Apparently. I wasn't aware of that, but it makes sense to treat it that way instead of creating a new operator `?:`. – deceze Apr 28 '14 at 13:17
  • Interesting how you use stuff for a long time, only to discover much later -WHY- it actually does what it does :) Never knew it returned the operator by default if the first statement is empty. Thx! – Damien Overeem Apr 28 '14 at 13:30
4

It is because of PHP 5.3

"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."

Ternary Operator

lagbox
  • 38,058
  • 7
  • 54
  • 64
1

The Elvis operator

There's some extra whitespace, but that syntax is commonly known as the elvis operator.

Consider the following:

$result = ($this ?: $that);

$result will be $this if $this is truthy, otherwise it will be $that.

Therefore when doing the equivalent of:

echo (true ?: 'some-test');

The result is always:

echo true;

Or the string "1".

Whitespace is not equivalent to null

Note that this:

$var = (true ?      : 'some-test');

is not equivalent to:

$var = (true ? null : 'some-test');

Only in the latter example will $var be null as it's a standard ternary if statement; the first statement is a huge-quiffed elvis operator.

Community
  • 1
  • 1
AD7six
  • 56,182
  • 12
  • 84
  • 114
0

var_dump(true ? : 'some-test'); is bool(true)

var_dump('test' . true); is string(5) "test1"

This part is clear I hope. What's strage here is that true ? : 'some-test' evaluates to true. This is a new behavior introduced in PHP 5.3 where if you omit the middle expression the value of the first one (true in your case) is returned.

Sergiu Paraschiv
  • 9,575
  • 5
  • 33
  • 45