- Wednesday, 2019-01-02 13:35
- 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;So do these two:
$result = $input ?: $fallback;$result = isset( $input ) && $input !== null ? $input : $fallback;In other words, there are two differences:
$result = $input ?? $fallback;
?:relies on PHP's somewhat »magic« behavior to not only consider
nulland the number 0 »falsy« values, but also empty arrays, empty strings, as well as the string
??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.
Kommentare zu diesem Beitrag können per E-Mail an den Autor gesandt werden.