phpif-statementcontrol-structureshorthand-if

Why is an empty value in a shorthand if-then-else returning `true`?


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 ?


Solution

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