HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Logical Operators

Logical operators are used to combine conditional statements. They allow you to test multiple conditions at once and decide whether a complex piece of logic should execute. They are the "connectives" of programming.


Table of Logical Operators

PHP supports the following logical operators:

Operator Name Description
and And True if both $x and $y are true
or Or True if either $x or $y is true
xor Xor True if either $x or $y is true, **but not both**
! Not True if $x is not true
&& And True if both $x and $y are true
|| Or True if either $x or $y is true

Understanding && vs. and

You might notice that PHP has two operators for "And" and "Or" (e.g., && and and). The technical difference between them is Operator Precedence.

  • The symbols && and || have **high precedence**.
  • The words and and or have **low precedence**.
Pro Tip: In modern web development, && and || are almost always preferred because they behave more consistently with other languages like JavaScript.

XOR — The Exclusive Or

The xor operator is unique. It only returns true if exactly one of the conditions is true. If both are true, it returns false.

<?php
    $x = true;
    $y = true;

    if ($x xor $y) {
        echo "This will NOT print because both are true.";
    }
?>

The NOT Operator (!)

The ! operator reverses the logic. It turns `true` into `false` and `false` into `true`.

<?php
    $isLoggedIn = false;

    if (!$isLoggedIn) {
        echo "Please log in to continue.";
    }
?>
Important: Logical operators are almost always used inside if statements, while loops, or for validating multiple form requirements (like a password being long enough AND containing a number).

Key Points to Remember

  • Use && / and when all conditions must be met.
  • Use || / or when any one condition is enough.
  • ! (Not) is used to toggle or reverse a logical outcome.
  • XOR is for situations where you want exactly one condition to be true.
  • Symbolic operators (&&, ||) have higher priority than word-based operators.