PHP ternary operator vs null coalescing operator

后端 未结 13 1814
南笙
南笙 2020-11-22 15:58

Can someone explain the differences between ternary operator shorthand (?:) and null coalescing operator (??) in PHP?

When do they behave d

13条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 16:22

    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.

提交回复
热议问题