邏輯運算符通常用于條件判斷,基本用法如下:
// 定義變量
$foo = TRUE;
$bar = FALSE;
// 邏輯與,必須兩者都為TRUE
$foo and $bar; // false
$foo && $bar; // false
// 邏輯或,兩者任意其一為TRUE
$foo or $bar; // true
$foo || $bar; // true
// 邏輯非,取反向的布爾型結果
!$bar; // true
// 邏輯異或,兩者任意其一為TRUE,但不能同時是
$foo xor $bar; // true
在處理邏輯運算符的問題上,需要特別注意幾點:
一:優先級問題,建議參考官方運算符優先級。
$foobar = 0 or 'hello world';
// 輸出0,因為 = 優先級大于 or
echo $foobar;
$foobar = 0 || 'hello world';
// 輸出1,因為 = 優先級小于 ||
echo $foobar;
二:PHP將以 從左到右 的方式進行判斷。
$foobar = TRUE ? 'hello' : FALSE ? 'foo' : 'bar';
// 輸出 foo
echo $foobar;
// 上例在PHP看來會是這個樣子
$foobar = (TRUE ? 'hello' : FALSE) ? 'foo' : 'bar';
三:邏輯與 中只要其一為 FALSE
,將停止判斷立刻返回結果。
function foo(){
echo 'hello';
return false;
}
function bar(){
echo 'world';
return true;
}
// 輸出 hello
foo() and bar();
四:邏輯或 中只要其一為 TRUE
,將停止判斷立刻返回結果。
function foo(){
echo 'hello';
return true;
}
function bar(){
echo 'world';
return false;
}
// 輸出 hello
foo() or bar();
五:邏輯判斷比較的是布爾型值,所以其他類型的變量在進行判斷時會自動轉成布爾值進行判斷并返回。
// 輸出1,因為`hello world`被轉成布爾型 TRUE 了
echo 0 || 'hello world';