[php] Logical Operators, || or OR?

I remember reading a while back in regards to logical operators that in the case of OR, using || was better than or (or vice versa).

I just had to use this in my project when it came back to me, but I can't remember which operator was recommended or if it was even true.

Which is better and why?

This question is related to php operators logical-operators or-operator

The answer is


There is nothing bad or better, It just depends on the precedence of operators. Since || has higher precedence than or, so || is mostly used.


They are used for different purposes and in fact have different operator precedences. The && and || operators are intended for Boolean conditions, whereas and and or are intended for control flow.

For example, the following is a Boolean condition:

if ($foo == $bar && $baz != $quxx) {

This differs from control flow:

doSomething() or die();

Some languages use short-circuit, and others use full Boolean evaluation (if you know, this is similar to the directive $B in Pascal).

Explanations:

function A(){
    ...Do something..
    return true;
}

function B(){
    ...Do something..
    return true;
}

if ( A() OR B() ) { .....

In this example the function B() will never be executed. Since the function A() returns TRUE, the result of the OR statement is known from the first part without it being necessary to evaluate the second part of the expression.

However with ( A() || B() ), the second part is always evaluated regardless of the value of the first.

For optimized programming, you should always use OR which is faster (except for the case when the first part returns false and second part actually needs to be evaluated).


Source: http://wallstreetdeveloper.com/php-logical-operators/

Here is sample code for working with logical operators:

<html>

<head>
    <title>Logical</title>
</head>

<body>
    <?php
        $a = 10;
        $b = 20;
        if ($a>$b)
        {
            echo " A is Greater";
        }
        elseif ($a<$b)
        {
            echo " A is lesser";
        }
        else
        {
             echo "A and B are equal";
        }
    ?>
    <?php
        $c = 30;
        $d = 40;
        //if (($a<$c) AND ($b<$d))
        if (($a<$c) && ($b<$d))
        {
            echo "A and B are larger";
        }
        if (isset($d))
            $d = 100;
        echo $d;
        unset($d);
    ?>
    <?php
        $var1 = 2;
        switch($var1)
        {
            case 1:  echo "var1 is 1";
                     break;
            case 2:  echo "var1 is 2";
                     break;
            case 3:  echo "var1 is 3";
                     break;
            default: echo "var1 is unknown";
        }
    ?>
</body>
</html>

I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.

EDIT: As others have pointed out there is indeed a difference between the two.


The difference between respectively || and OR and && and AND is operator precedence :

$bool = FALSE || TRUE;

  • interpreted as ($bool = (FALSE || TRUE))
  • value of $bool is TRUE

$bool = FALSE OR TRUE;

  • interpreted as (($bool = FALSE) OR TRUE)
  • value of $bool is FALSE

$bool = TRUE && FALSE;

  • interpreted as ($bool = (TRUE && FALSE))
  • value of $bool is FALSE

$bool = TRUE AND FALSE;

  • interpreted as (($bool = TRUE) AND FALSE)
  • value of $bool is TRUE

I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...

Let's say the code looks like this:

$positions = $this->positions() || [];

You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.

If you need to get value of $this->positions() or empty array, you have to use:

$positions = $this->positions() or [];

EDIT:

The above example doesn't work as intended but the truth is that || and or is not the same... Try this:

<?php

function returnEmpty()
{
  //return "string";
  //return [1];
  return null;
}

$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];

var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";

This is the result:

bool(false)
NULL
array(0) {
}

So, actually the third option ?: is the correct solution when you want to set returned value or empty array.

$positions = $this->positions() ?: [];

Tested with PHP 7.2.1


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to operators

What is the difference between i = i + 1 and i += 1 in a 'for' loop? Using OR operator in a jquery if statement What is <=> (the 'Spaceship' Operator) in PHP 7? What does question mark and dot operator ?. mean in C# 6.0? Boolean operators ( &&, -a, ||, -o ) in Bash PowerShell and the -contains operator How do I print the percent sign(%) in c Using the && operator in an if statement What do these operators mean (** , ^ , %, //)? How to check if div element is empty

Examples related to logical-operators

Javascript logical "!==" operator? Java logical operator short-circuiting Boolean operators && and || Simple logical operators in Bash Logical Operators, || or OR? Differences in boolean operators: & vs && and | vs || Python's equivalent of && (logical-and) in an if-statement Logical operators ("and", "or") in DOS batch Logical XOR operator in C++? What's the difference between & and && in MATLAB?

Examples related to or-operator

Boolean operators && and || Logical Operators, || or OR? What does the construct x = x || y mean? JavaScript OR (||) variable assignment explanation