简体   繁体   中英

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 ?

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

foo ? : bar 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 foo ? null : bar .

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM