PHP Logical Operators
In this page:
Logical AND (&&, and)
&& (or the word and) only evaluates to true when both sides are true, and PHP short-circuits it: if the left side is already false, the right side never even runs. That short-circuiting is why && is commonly used to guard against errors, e.g. isset($x) && $x > 0.
Example: Logical AND (&&, and)
<?php
$x = 5;
if (isset($x) && $x > 0) {
echo "x is set and positive";
}
?>
Login to try C/C++/Java/PHP code in the editor
Logical OR (||, or)
|| (or or) evaluates to true the moment *either* side is true, and it short-circuits the opposite way — if the left side is already true, PHP never bothers evaluating the right side at all, which can matter if that right side has side effects.
Example: Logical OR (||, or)
<?php
$loggedIn = false;
$isAdmin = true;
if ($loggedIn || $isAdmin) {
echo "Access granted";
}
?>
Login to try C/C++/Java/PHP code in the editor
Logical NOT (!)
! inverts a single boolean on its own — true becomes false and vice versa. It's most often seen prefixing a function call or condition to flip its meaning directly, as in if (!isset($value)), read as 'if value is not set.'
Example: Logical NOT (!)
<?php
$value = null;
if (!isset($value)) {
echo "value is not set";
}
?>
Login to try C/C++/Java/PHP code in the editor
Logical XOR (xor)
xor returns true only when exactly one side is true — both true or both false both produce false. It's less common than &&/|| in everyday code, but it's exactly the right tool when a rule genuinely means 'one or the other, but not both.'
Example: Logical XOR (xor)
<?php
var_dump(true xor false);
var_dump(true xor true);
?>
Login to try C/C++/Java/PHP code in the editor
Combining Logical Operators
PHP evaluates logical operators left to right according to precedence rules, and those rules aren't always what you'd guess — and/or bind more loosely than &&/||. Wrapping sub-expressions in parentheses removes any ambiguity and makes the intended grouping obvious to a reader too.
Example: Combining Logical Operators
<?php
$a = true;
$b = false;
$c = true;
echo ($a && $b) || $c ? "true" : "false";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: