PHP ternary operator vs null coalescing operator

后端 未结 13 1884
南笙
南笙 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:23

    For the beginners:

    Null coalescing operator (??)

    Everything is true except null values and undefined (variable/array index/object attributes)

    ex:

    $array = [];
    $object = new stdClass();
    
    var_export (false ?? 'second');                           # false
    var_export (true  ?? 'second');                           # true
    var_export (null  ?? 'second');                           # 'second'
    var_export (''    ?? 'second');                           # ""
    var_export ('some text'    ?? 'second');                  # "some text"
    var_export (0     ?? 'second');                           # 0
    var_export ($undefinedVarible ?? 'second');               # "second"
    var_export ($array['undefined_index'] ?? 'second');       # "second"
    var_export ($object->undefinedAttribute ?? 'second');     # "second"
    

    this is basically check the variable(array index, object attribute.. etc) is exist and not null. similar to isset function

    Ternary operator shorthand (?:)

    every false things (false,null,0,empty string) are come as false, but if it's a undefined it also come as false but Notice will throw

    ex

    $array = [];
    $object = new stdClass();
    
    var_export (false ?: 'second');                           # "second"
    var_export (true  ?: 'second');                           # true
    var_export (null  ?: 'second');                           # "second"
    var_export (''    ?: 'second');                           # "second"
    var_export ('some text'    ?? 'second');                  # "some text"
    var_export (0     ?: 'second');                           # "second"
    var_export ($undefinedVarible ?: 'second');               # "second" Notice: Undefined variable: ..
    var_export ($array['undefined_index'] ?: 'second');       # "second" Notice: Undefined index: ..
    var_export ($object->undefinedAttribute ?: 'second');     # "Notice: Undefined index: ..
    

    Hope this helps

提交回复
热议问题