逻辑运算符,|| 还是OR?

drp*_*ken 97 php operators logical-operators or-operator

我记得有一段时间关于逻辑运算符的回顾,在这种情况下OR,使用||优于or(反之亦然).

当我回到我身边时,我只能在我的项目中使用它,但我不记得推荐哪个运算符,或者它是否真实.

哪个更好?为什么?

Fel*_*ing 132

没有"更好",但更常见的是||.它们具有不同的优先级,并且||可以像人们通常期望的那样工作.

另请参见:逻辑运算符(以下示例取自此处):

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
Run Code Online (Sandbox Code Playgroud)

  • 和`$ e = true || $ x ='foo'`不会因为短路而定义`$ x`,而不是因为优先级更高. (8认同)
  • 还值得注意的是,这些 * 总是 * 返回一个布尔值,与许多其他语言不同,它们返回检查的最后一个值。所以在 PHP (27 || 0) 中返回 *true*,而不是 *27*。 (4认同)
  • @TextGeek,“这些”?“27 或 0” 对我来说返回“27”。 (2认同)
  • @TextGeek,实际上,您对,`or`也返回布尔值。只是它的优先级如此之低,以至于有时看起来像是在做其他事情。:)`print 27 or 0`将打印`27`,因为`or`发生在after_print 27中。顺便说一句,`echo`不会被欺骗-`echo 27 or 0`将输出`1`。 (2认同)

Mat*_*off 40

它们用于不同的目的,实际上具有不同的运算符优先级.的&&||运营商意图用于布尔条件,而andor旨在用于控制流程.

例如,以下是布尔条件:

if ($foo == $bar && $baz != $quxx) {
Run Code Online (Sandbox Code Playgroud)

这与控制流程不同:

doSomething() or die();
Run Code Online (Sandbox Code Playgroud)

  • `doSomething()`被评估为布尔值.如果它返回一个值PHP认为truthy(`true`,非空字符串等),它将不会调用`die()`. (5认同)

Joh*_*ers 20

分别为||的区别 和OR和&&和AND是运算符优先级:

$bool = FALSE || TRUE;

  • 解释为 ($bool = (FALSE || TRUE))
  • 价值$boolTRUE

$bool = FALSE OR TRUE;

  • 解释为 (($bool = FALSE) OR TRUE)
  • 价值$boolFALSE

$bool = TRUE && FALSE;

  • 解释为 ($bool = (TRUE && FALSE))
  • 价值$boolFALSE

$bool = TRUE AND FALSE;

  • 解释为 (($bool = TRUE) AND FALSE)
  • 价值$boolTRUE


小智 5

资料来源:http://bit.ly/1hxDmVR

以下是使用逻辑运算符的示例代码:

<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>
Run Code Online (Sandbox Code Playgroud)