I’m getting the error "Undefined array key "name" in the following code:
if ($arr & $arr['name']??'')
Shouldn’t the null coalescing operator prevent that error if the array key doesn’t exist??
I tried using isset() instead and it did not return an error. But what gives?
I’ve used the null coalescing operator loads before and never had any problems with it. I don’t understand what is different about this code?
2
Answers
The null coalesce operator does not produce a warning/error.
As stated in https://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce, the coalesce is identical to using
isset()
. You have a&
instead of&&
in the code.Regardless of the use of
&
versus&&
, those operators have a higher precedence than the??
operator. So this:Evaluates to this:
Which means PHP tries first to evaluate
$arr['name']
outside the context of the null coalesce, so you get the notice. You can force the desired precedence with explicit parens:That said, the explicit check for
$arr
is generally not needed when you use null coalesce, so what you probably want is simply:Which basically means, "if a value is present and not empty."