简体   繁体   中英

PHP Null coalescing operator confusion

I'm a bit confused. The PHP documenation says:

// Example usage for: Null Coalesce Operator
$action = $_POST['action'] ?? 'default';

// The above is identical to this if/else statement
if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    $action = 'default';
}

But my own example says something very different:

echo "<pre>";
$array['intValue'] = time();
$array['stringValue'] = 'Hello world!';
$array['boolValue'] = false;


$resultInt = isset($array['intValue']) ?? -1;
$resultString = isset($array['stringValue']) ?? 'Another text';
$resultBool = isset($array['boolValue']) ?? true;

var_dump($resultInt);
var_dump($resultString);
var_dump($resultBool);

echo '<br/>';

if(isset($array['intValue'])) $_resultInt = $array['intValue'];
else $_resultInt = -1;

if(isset($array['stringValue'])) $_resultString = $array['stringValue'];
else $_resultString = 'Another text';

if(isset($array['boolValue'])) $_resultBool = $array['boolValue'];
else $_resultBool = true;


var_dump($_resultInt);
var_dump($_resultString);
var_dump($_resultBool);

echo "</pre>";

My output:

bool(true)
bool(true)
bool(true)

int(1534272962)
string(12) "Hello world!"
bool(false)

So, as my example shows, the if-condition does not result in the same as the null coalescing operator does as the documentation says. Can somebody explain me, what I did wrong?

Thank you!

You're doing:

$resultInt = isset($array['intValue']) ?? -1;
$resultString = isset($array['stringValue']) ?? 'Another text';
$resultBool = isset($array['boolValue']) ?? true;

But the point of ?? is that it does the isset call for you. So try this, just put the values without using isset :

$resultInt = $array['intValue'] ?? -1;
$resultString = $array['stringValue'] ?? 'Another text';
$resultBool = $array['boolValue'] ?? true;

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