1

I am trying to understand how the null coalescing operator does really work. So, I tested many examples after reading the documentation in php.net and some posts on stackoverflow.

However, I can't understand this code:

<?php 
$x = false ?? 'stackoverflow';
var_dump($x); // bool(false)

since it's equivalent to (from php.net#null-coalescing)

isset(false) ? false : 'stackoverflow';

and since isset(false) generates a fatal error.

Could, please, someone explain to me?

4
  • Being 'equivalent to' does not mean the same as. Commented May 17, 2018 at 13:52
  • from the docs: "In particular, this operator does not emit a notice if the left-hand side value does not exist, just like isset(). This is especially useful on array keys." Commented May 17, 2018 at 13:55
  • Like it says, it's syntactic sugar for a common use-case of using a ternary operator in conjunction with isset. If that's not what you're doing, this isn't the operator you need. The docs could possibly be worded a little better, in fairness. Commented May 17, 2018 at 13:55
  • Note that it is named the "Null Coalescing Operator", not the "False Coalescing Operator". Commented May 17, 2018 at 18:06

1 Answer 1

2

Null coalescing operator returns its first operand if it exists and is not NULL;

Otherwise it returns its second operand.

In your case first operand is false so it is assigned to the variable. For e.g; if you initialize null to first operand then it will assign second operands value as shown.

 $a = null;
 $x = $a ?? 'abc';
 var_dump($x);

Result :
string(3) "abc" 
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.