$a ?: $b
is short-hand for $a ? $a : $b
which is not quite the same as !empty($a) ? $a : $b
The difference between them requires careful reading of the definition of the empty
pseudo-function:
Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals false. empty() does not generate a warning if the variable does not exist.
When you just use $a
"in boolean context", as in if ( $a )
or $a ? $a : $b
or $a ?: $b
, its value will be converted to boolean. If the variable doesn't exist - a mistyped variable name, for instance - a Warning will be issued while retrieving that value.
The special power of the empty()
pseudo-function is that it won't give you that Warning. The actual result will be the same - an unset variable is considered "equal to false" - but the two pieces of code aren't always interchangeable.