Search code examples
phplogical-operatorsoperator-precedence

Do PHP's logical operators work as JavaScript's?


One of the things I like the most of JavaScript is that the logical operators are very powerful:

  • && can be used to safely extract the value of an object's field, and will return null if either the object or the field has not been initialized

    // returns null if param, param.object or param.object.field
    // have not been set
    field = param && param.object && param.object.field;
    
  • || can be used to set default values:

    // set param to its default value
    param = param || defaultValue;
    

Does PHP allow this use of the logical operators as well?


Solution

  • PHP returns true orfalse. But you can emulate JavaScript's r = a || b || c with:

    $r = $a ?: $b ?: $c;
    

    Regarding 'ands', something like:

    $r = ($a && $a->foo) ? $a->foo->bar : null;