1

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!

1 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.