Home » Php » Do PHP's logical operators work as JavaScript's?

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

Posted by: admin July 12, 2020 Leave a comment


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?

How to&Answers:

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;


PHP logical operators do not return the value on any of their sides : they will always get you a boolean.

For instance, doing :

$result = $a && $b;

Will always make $result contain a boolean : true or false — and never $a nor $b.


You can set up similar functionality using ternary operators.



With respect to logical ANDing in PHP to achieve the same kind of result as JavaScript, you could use a variant of the traditional ternary, as follows:

    // prelim
    $object = new stdClass;
    $object->field = 10;
    $param = new stdClass;
    $param->object = $object;

    // ternary variant     
    $field = !($param && $param->object)?:  $param->object->field;
    echo $field,"\n";

    // alternative to ANDing
    $field = get_object_vars( $param->object )["field"] ?? null;
    echo $field,"\n";

See live code

The “Elvis” operator “?:” only assigns the result to $field if the conditional expression is false. So, if $param exists as well as $param->object, then you have to use the NOT operator (“!”) in order to get the desired result.

You may also accomplish the objective of getting the field data without ANDing by utilizing the null coalescing operator (“??”) in PHP 7 in tandem with get_object_vars().