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.
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 |
You might notice that PHP has two operators for "And" and "Or" (e.g., && and and). The technical difference between them is Operator Precedence.
&& and || have **high precedence**.and and or have **low precedence**.&& and || are almost always preferred because they behave more consistently with other languages like JavaScript.
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 ! operator reverses the logic. It turns `true` into `false` and `false` into `true`.
<?php
$isLoggedIn = false;
if (!$isLoggedIn) {
echo "Please log in to continue.";
}
?>
if statements, while loops, or for validating multiple form requirements (like a password being long enough AND containing a number).
&&, ||) have higher priority than word-based operators.