AND和&&之间的区别

3

考虑以下陈述:

if($value && array_key_exists($value, $array)) {

         $hello['world'] = $value;

        }

在使用逻辑操作符时,与其使用 && 运算符,使用 AND 运算符是否更佳?


1
它们的功能是相同的,所以选择哪一个并坚持使用它其实并不重要。这是我的建议。 - Dan
可能是PHP - and / or 关键字的重复问题。 - Gordon
4个回答

11

它们本身的作用是完全相同的。因此,a && b的意思与a and b相同。但是,它们并不完全相同,因为&&的优先级高于and。有关详细信息,请参见文档

这里的示例显示了它们之间的区别:

// 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) and true)
$f = false and true;

3

在条件语句中它们是相同的,但在条件赋值中要小心

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

// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;

并且

// 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;

从你链接的逻辑运算符手册中。

3
您提供的链接有一个注释:

“and”和“or”运算符有两种不同的变体,原因是它们具有不同的优先级。(请参阅运算符优先级。)

在您的情况下,由于这是唯一的运算符,取决于您,但它们并不完全相同。


1

只有拼写上的差异..使用 && 而不是 ANDand 是一个好的编程习惯..


如果您能详细说明原因,那就太好了。 - icktoofay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接