Can someone explain the differences between ternary operator shorthand (?:
) and null coalescing operator (??
) in PHP?
When do they behave d
Both are shorthands for longer expressions.
?:
is short for $a ? $a : $b
. This expression will evaluate to $a if $a evaluates to TRUE.
??
is short for isset($a) ? $a : $b
. This expression will evaluate to $a if $a is set and not null.
Their use cases overlaps when $a is undefined or null. When $a is undefined ??
will not produce an E_NOTICE, but the results are the same. When $a is null the result is the same.