PHP
⚡ Logical Operators in PHP
Logical Operators in PHP are used to combine multiple conditional statements into a single result. Evaluating logical expressions yields a boolean outcome (true or false). They form the core logic inside decision-making structures like if, while, and for loops.
-
Operator Precedence Caution: Always prefer
&&and||overandandor. Symbolic operators have higher precedence than the assignment operator (=), preventing subtle bug behaviors during evaluation.
🛠️ Basic Logical Operators and Syntax
1️⃣ Logical AND (&& / and)
Returns true only if every evaluated condition is true.
var_dump(true && true); // Outputs: bool(true)
var_dump(true && false); // Outputs: bool(false)
2️⃣ Logical OR (|| / or)
Returns true if at least one condition evaluates to true.
var_dump(true || false); // Outputs: bool(true)
var_dump(false || false); // Outputs: bool(false)
3️⃣ Exclusive OR (xor)
Returns true if either condition is true, but NOT both.
var_dump(true xor false); // Outputs: bool(true)
var_dump(true xor true); // Outputs: bool(false)
var_dump(false xor false); // Outputs: bool(false)
4️⃣ Logical NOT (!)
Reverses the boolean state of a condition.
var_dump(!true); // Outputs: bool(false)
var_dump(!false); // Outputs: bool(true)
⚠️ Difference Between (&& / ||) and (and / or)
The word-based operators (and, or) have lower precedence than the assignment operator (=), which can lead to unexpected variable bindings:
// Correct behavior using symbolic AND (&&)
$result1 = true && false;
// $result1 becomes false
// Unexpected behavior using word-based AND (and)
$result2 = true and false;
// ($result2 = true) is executed first! $result2 becomes true
💡 Real-World Practical Example
Validating multi-step user conditions in business logic:
$age = 20;
$hasLicense = true;
if ($age >= 18 && $hasLicense === true) {
echo "Eligible to drive a vehicle.";
} else {
echo "Not eligible to drive.";
}
📊 Logical Operators Reference Table
| Operator | Name | Meaning | When Is It True? |
|---|---|---|---|
&& / and |
AND | And | True only if all conditions are true |
|| / or |
OR | Or | True if at least one condition is true |
xor |
XOR | Exclusive OR | True if only one condition is true (not both) |
! |
NOT | Not | True if the evaluated condition is false |
-
📝 Short Summary
- Logical operators group individual evaluations into boolean decisions.
-
Use
&&and||in production environments to avoid precedence issues during variable assignment. -
The
!operator toggles boolean truthiness, useful for checking falsey values or inverted conditions.
