考虑以下陈述:
if($value && array_key_exists($value, $array)) {
$hello['world'] = $value;
}
在使用逻辑操作符时,与其使用 && 运算符,使用 AND 运算符是否更佳?
考虑以下陈述:
if($value && array_key_exists($value, $array)) {
$hello['world'] = $value;
}
在使用逻辑操作符时,与其使用 && 运算符,使用 AND 运算符是否更佳?
它们本身的作用是完全相同的。因此,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;
在条件语句中它们是相同的,但在条件赋值中要小心:
// 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;
“and”和“or”运算符有两种不同的变体,原因是它们具有不同的优先级。(请参阅运算符优先级。)
在您的情况下,由于这是唯一的运算符,取决于您,但它们并不完全相同。
只有拼写上的差异..使用 && 而不是 AND 或 and 是一个好的编程习惯..