Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

ความแตกต่างระหว่าง AND และ && ใน PHP (Operator Precedence)

ทั้ง AND และ && เป็น Logical AND Operator แต่มี Precedence (ลำดับความสำคัญ) ต่างกัน

ความแตกต่างหลัก: Precedence

OperatorPrecedenceความหมาย
&&High (สูง)ประเมินก่อน Assignment (=)
ANDLow (ต่ำ)ประเมินหลัง Assignment (=)

ตัวอย่างแสดงความแตกต่าง

 แต่ค่าของ $result ยังคงเป็น true!

var_dump($result); // bool(true)  <-- ผลต่างกัน!

ตารางความจริง (Truth Table)

กฎการใช้งาน (Best Practice)

  1. ใช้ && และ || เป็นหลัก - เป็นมาตรฐานในภาษาโปรแกรมส่วนใหญ่ (C, Java, JS, Go, Rust)
  2. ใช้ AND / OR เฉพาะใน Control Flow เช่น doSomething() AND doAnother()
  3. ไม่ควรผสม && กับ AND ใน Expression เดียว
  4. ใช้ 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)