|| vs or|| 優先級高於賦值(=),or 優先級低於賦值。導致同樣邏輯賦值結果截然不同。
$choice1 = "wdphp.com";
$choice2 = "";
$default = "vducn.com";
$val_1 = $choice1 || $choice2 || $default; // 邏輯運算結果:true(1)
$val_2 = $choice1 or $choice2 or $default; // 賦值結果:$choice1 的值 "wdphp.com"
$val_3 = ($choice1 or $choice2 or $default); // 括號提升優先級:true(1)
echo "val_1=$val_1 val_2=$val_2 val_3=$val_3";
// 輸出:val_1=1 val_2=wdphp.com val_3=1
or 的行為function foo() { return 0; }
function bar() { return 1; }
$x_1 = foo() or bar(); // $x_1 = 0 (foo 的回傳值)
$x_2 = $x_1 or bar(); // $x_2 = 0 ($x_1 的值)
$x_3 = ($x_1 or bar()); // $x_3 = 1 (邏輯運算結果)
echo "x_1=$x_1 x_2=$x_2 x_3=$x_3";
// 輸出:x_1=0 x_2=0 x_3=1
if 的寫法is_array($variable) or notAnArray();
function notAnArray() { echo "This is not an array"; }
利用短路特性:左側為假才執行右側。僅適用於簡單邏輯,複雜流程請用 if/else 保持可讀性。
||、&&。or、and,但需完全理解優先級。