← Back to PHP Course | Chapter 3: Operators | Lesson 3 of 8

PHP Logical Operators

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
<?php
$x = 5;
if (isset($x) && $x > 0) {
    echo "x is set and positive";
}
?>

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
<?php
$loggedIn = false;
$isAdmin = true;
if ($loggedIn || $isAdmin) {
    echo "Access granted";
}
?>

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
<?php
$value = null;
if (!isset($value)) {
    echo "value is not set";
}
?>

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
<?php
var_dump(true xor false);
var_dump(true xor true);
?>

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
<?php
$a = true;
$b = false;
$c = true;
echo ($a && $b) || $c ? "true" : "false";
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.