0

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?

Onitech
  • 85
  • 1
  • 15
  • 1
    in the first example it returns the expression `($complete == 'complete')` which resolves to true/1. The others return `$complete`. (I suppose that's a typo in the second example: `..? $completeD :..` – Jeff Apr 16 '18 at 10:27

2 Answers2

4

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';
}
eisbehr
  • 12,243
  • 7
  • 38
  • 63
0

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.