ทั้ง AND และ && เป็น Logical AND Operator แต่มี Precedence (ลำดับความสำคัญ) ต่างกัน
ความแตกต่างหลัก: Precedence
| Operator | Precedence | ความหมาย |
|---|---|---|
&& | High (สูง) | ประเมินก่อน Assignment (=) |
AND | Low (ต่ำ) | ประเมินหลัง Assignment (=) |
ตัวอย่างแสดงความแตกต่าง
แต่ค่าของ $result ยังคงเป็น true!
var_dump($result); // bool(true) <-- ผลต่างกัน!
ตารางความจริง (Truth Table)
กฎการใช้งาน (Best Practice)
- ใช้
&&และ||เป็นหลัก - เป็นมาตรฐานในภาษาโปรแกรมส่วนใหญ่ (C, Java, JS, Go, Rust) - ใช้
AND/ORเฉพาะใน Control Flow เช่นdoSomething() AND doAnother() - ไม่ควรผสม && กับ AND ใน Expression เดียว
- ใช้ Parentheses เพื่อความชัดเจน:
($a && $b) || $c
ตัวอย่างการใช้งานที่เหมาะสม
// ✅ ดี: ใช้ && สำหรับ Expression/Assignment
$isValid = $user->isActive() && $user->hasPermission('read');
// ✅ ดี: ใช้ AND สำหรับ Control Flow (Short-circuit)
$connected = connectToDB() AND logConnection(); // logConnection รันต่อเมื่อ connect สำเร็จ
// ✅ ดี: ใช้ OR สำหรับ Default Value (Short-circuit)
$config = loadConfig() OR $config = getDefaultConfig();
// ❌ หลีกเลี่ยง: Assignment กับ AND
$result = $a AND $b; // Confusing!
Precedence Table (บางส่วน)
Highest: clone, new, [, ], (, )
**, ++, --, ~, @, (int), (float), (string), (array), (object), (bool)
*, /, %
+, -, .
<<, >>
<, <=, >, >=
==, !=, ===, !==, <>, <=>
&
^
|
&&
||
? : (Ternary)
=, +=, -=, *=, /=, .=, %=, &=, |=, ^=, <<=, >>=
AND
XOR
OR
Lowest: , (comma)