PHP Logical Operators
Logical operators combine multiple boolean expressions. They're essential for creating complex conditions in if statements, loops, and other control structures!
Logical Operators Overview
| Operator | Name | Description | Example |
|---|---|---|---|
&& |
AND | True if both are true | true && false โ false |
|| |
OR | True if at least one is true | true || false โ true |
! |
NOT | Inverts boolean value | !true โ false |
and |
AND | Same as && (lower precedence) | true and false โ false |
or |
OR | Same as || (lower precedence) | true or false โ true |
xor |
XOR | True if exactly one is true | true xor false โ true |
Output
Click Run to execute your code
AND Operator (&&)
Returns true only if BOTH conditions are true:
<?php
$age = 25;
$hasLicense = true;
if ($age >= 18 && $hasLicense) {
echo "Can drive!";
}
// Truth table for AND
var_dump(true && true); // true
var_dump(true && false); // false
var_dump(false && true); // false
var_dump(false && false); // false
?>
OR Operator (||)
Returns true if AT LEAST ONE condition is true:
<?php
$isWeekend = true;
$isHoliday = false;
if ($isWeekend || $isHoliday) {
echo "Day off!";
}
// Truth table for OR
var_dump(true || true); // true
var_dump(true || false); // true
var_dump(false || true); // true
var_dump(false || false); // false
?>
NOT Operator (!)
Inverts a boolean value:
<?php
$isLoggedIn = false;
if (!$isLoggedIn) {
echo "Please log in";
}
var_dump(!true); // false
var_dump(!false); // true
?>
Short-Circuit Evaluation
Important: PHP stops evaluating as soon as the result is known!
- AND (&&): Stops if first is false
- OR (||): Stops if first is true
<?php
// Second condition never evaluated
false && expensiveFunction(); // expensiveFunction() not called
// Second condition never evaluated
true || expensiveFunction(); // expensiveFunction() not called
?>
Summary
- &&: AND - both must be true
- ||: OR - at least one must be true
- !: NOT - inverts boolean
- xor: XOR - exactly one must be true
- Short-circuit: Stops when result is known
- Precedence: ! > && > ||
What's Next?
Next, we'll learn about Increment and Decrement Operators - shortcuts for adding or subtracting 1 from variables!
Enjoying these tutorials?