Order of operations with null coalesce

This can be sneaky

Joel Clermont
Joel Clermont
2024-05-16

Another tip pulled from a recent discussion in the Mastering Laravel community.

Take a look at this block of (sanitized) code:

if ($obj !== null) {
    $x = $obj->prop['test']['aaa'] ?? 'default';
    $y = $obj->prop['test']['bbb'] ?? 'empty';
    $z = ! $obj->prop['test']['ccc'] ?? true;
}

This code was throwing the error Undefined array key "test", but only on the final line setting $z.

How could that line fail, but the ones before it not throw an error? What was happening?

I'll admit it: I didn't see the issue at first, but Aaron's keen eye caught it.

That ! operator was the culprit. Yes, I saw that line had the extra operator, but I didn't recognize why it was causing the error.

The null coalesce operator ?? has a lower precedence than the ! operator. So the expression was being evaluated as (! $obj->prop['test']['ccc']) ?? true.

Therefore, the null coalesce wasn't swallowing the error about the missing key. The error makes sense now!

And the fix was simple. Wrap the whole null coalesce expression in parentheses and put the ! operator on the outside to force the desired order of operations.

Here to help,

Joel

P.S. Can you tell I'm having a ton of fun in our Mastering Laravel community?

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼

Level up your Laravel skills!

Each 2-minute email has real-world advice you can use.