Can someone explain the differences between ternary operator shorthand (?:
) and null coalescing operator (??
) in PHP?
When do they behave d
Scroll down on this link and view the section, it gives you a comparative example as seen below:
However, it is not advised to chain the operators as it makes it harder to understand the code when reading it later on.
The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.
Essentially, using the coalescing operator will make it auto check for null unlike the ternary operator.