maettig.com

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.

These two lines behave exactly the same:

$result = $input ? $input : $fallback;
$result = $input ?: $fallback;
So do these two:
$result = isset( $input ) && $input !== null ? $input : $fallback;
$result = $input ?? $fallback;
In other words, there are two differences:
  1. ?: 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.
  2. ?? 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.
Other than that, the two operators behave similar.
I was made aware of the fact that the additional `!== null` in my example is obsolete, because isset() already checks if a variable is, well, set *and* not null. I wanted to have it in my example for educational reasons, to make the behavior more obvious.
Thiemo

Kommentare zu diesem Beitrag können per E-Mail an den Autor gesandt werden.

[ < Zurück zur Übersicht ]

Impressum & Datenschutz