Ternary Operator(Elvis Operator) ?:

I'm just wondering why this code returns 1

$complete = 'complete';
$completed = ($complete == 'complete') ?: 'Not Complete';

while if I try this one

$complete = 'complete';
$completed = ($complete == 'complete') ? $complete : 'Not Complete';

and this one

$complete = 'complete';
if ($complete == 'complete') {
    $completed = $complete;
} else {
    $completed = 'Not Complete';
}

they both returns 'complete'

base on this ?: operator (the 'Elvis operator') in PHP

aren't they all supposed to return the same value?


This is because you make a boolean check in the first example:

$complete == 'complete' // returns 'true'

And the operator tells, if the statement is true, return the value of the statement, otherwise return 'not Complete'. So it does. And true is represented as 1 .

Explained by your examples:

// sets '$completed' to '($complete == 'complete')' what is 'true'
$completed = ($complete == 'complete') ?: 'Not Complete';

// sets '$completed' to '$completed', what is 'NULL', because '$completed' seems to be undefined before
$completed = ($complete == 'complete') ? $completed : 'Not Complete';

// sets '$completed' to the value of '$complete', because the statement is 'true'
if ($complete == 'complete') {
    $completed = $complete;
} else {
    $completed = 'Not Complete';
}

You can use Elvis Operator this way:

$completed = $complete ?: 'Not Complete';

In your code you have a statement like this case:

$completed = true ?: 'Not Complete';

therefore it returns true.

链接地址: http://www.djcxy.com/p/57736.html

上一篇: 我如何检查会话

下一篇: 三元运营商(猫王运营商)?: