Thiemo’s Weblog

PHP 7 introduced an ?? operator and calls it »null coalescing«, but it keeps confusing me for some reason. I mean, I know and love the ?: shortcut introduced in PHP 5.3 six years earlier. But what is the difference? I don't find the documentation terribly helpful.

?: relies on PHP's somewhat »magic« behavior to not only consider null and the number 0 »falsy« values, but also empty arrays, empty strings, as well as the string "0". ?? on the other hand only cares about null, nothing else.

?? suppresses warnings on the left hand side. This is useful when falling back to a default value for an array element that might not exist. But note this suppresses all warnings! The ?? operator should never have more complicated expressions on the left hand side because of this. ?: on the other hand reports undefined variables on both sides.