Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 147 ยท Operators

Logical Operators

Learn PHP logical operators - && (and), || (or), ! (not), xor, short-circuit evaluation, De Morgan's laws and the and/or precedence trap in assignments.

Real decisions rarely depend on one condition. A user can see a page if they're logged in and have the right role. A form is invalid if the email is missing or the password is too short. A discount applies if the cart is not empty. Logical operators combine booleans like these into a single true or false, so one if can express the whole rule.

PHP's core logical operators are && (and), || (or) and ! (not). They work like in most C-style languages, with one PHP-specific twist: there are also word versions, and, or and xor, which look friendlier but have a much lower precedence. That difference creates one of PHP's classic bugs, and this lesson shows it to you so you never write it. You'll also learn short-circuit evaluation, which lets you write safe checks like "the user exists and the user is an admin" in a single line.

This lesson uses comparisons from Comparison Operators and the truthy/falsy rules from Booleans and null.

&&, || and !

Operator Name Result is true when
$a && $b And both $a and $b are true
$a || $b Or at least one of them is true
!$a Not $a is false
$a xor $b Exclusive or exactly one of them is true
$a and $b And (low precedence) same as &&
$a or $b Or (low precedence) same as ||

Here's the complete truth table for the two-operand operators:

$a $b $a && $b $a || $b $a xor $b
true true true true false
true false false true true
false true false true true
false false false false false
PHP Combining conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The results are true, true and false, and the script prints Welcome in. Comparisons bind more tightly than && and ||, so you don't need parentheses around $age >= 18. Range checks like $age >= 13 && $age <= 19 are how you write "between" in PHP, since 13 <= $age <= 19 is a parse error.

Logical operators always return a boolean

In PHP, &&, ||, ! and xor always return true or false, never one of their operands. Non-boolean operands are converted using the truthy/falsy rules first:

PHP Results are always booleans

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

If you know JavaScript, the third block is the important one. In JavaScript, name || 'Guest' gives you 'Guest'. In PHP it gives you bool(true), which is useless as a display name. For "this value, or a default", PHP has dedicated operators: ?: (the short ternary, which falls back on any falsy value) and ?? (null coalescing, which falls back only on null or a missing value). Both are covered in Null Coalescing, Ternary and Nullsafe Operators.

!!$value is a compact way to convert a value to a boolean, but (bool) $value says the same thing more clearly.

Short-circuit evaluation

PHP evaluates logical expressions from left to right and stops as soon as the answer is known:

  • For $a && $b, if $a is false, the result must be false, so $b is never evaluated.
  • For $a || $b, if $a is true, the result must be true, so $b is never evaluated.

This matters when the right side is a function call, or when it would fail if the left side were false:

PHP Short-circuiting in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output shows which checks actually ran:

TEXT
AND with a false first operand:
  checking A
bool(false)
OR with a true first operand:
  checking C
bool(true)
AND with a true first operand:
  checking E
  checking F
bool(false)

B and D never print, because PHP didn't need them. Short-circuiting is what makes guard conditions safe: you test that something exists before you use it, in the same expression.

PHP Guard conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each condition protects the next one. For null, $user['roles'] is never read. For the empty array, $items[0] is never accessed, so there's no Undefined array key warning. And 100 / $divisor never runs with a zero divisor, so there's no DivisionByZeroError. Swap the order of any of these pairs and the script breaks.

Two practical tips follow from short-circuiting:

  • Put cheap tests first and expensive ones (database queries, file reads) last, so the expensive work is skipped when possible.
  • Don't hide side effects you rely on in the right-hand operand. In $valid && saveToDatabase($row), the save runs only when $valid is true. That can be intentional, but an if statement makes it much clearer.

Negation and De Morgan's laws

! flips a boolean. It binds very tightly (more tightly than comparisons), which leads to a subtle bug:

PHP
$count = 5;
var_dump(!$count > 3);     // bool(false): means (!$count) > 3, i.e. false > 3
var_dump(!($count > 3));   // bool(false), but for the right reason
var_dump(!($count > 10));  // bool(true)

When you negate a comparison, wrap it in parentheses, or better, use the opposite operator: $count <= 3 instead of !($count > 3).

For negating combined conditions, De Morgan's laws tell you how to push the ! inside:

  • !($a && $b) is the same as !$a || !$b
  • !($a || $b) is the same as !$a && !$b
PHP De Morgan's laws for clearer conditions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Both if statements test the same thing, and both print. The second version is easier to read because there's no negation to untangle: "the email is empty, or the password is too short".

The and/or precedence trap

The word operators and, or and xor do the same logic as && and ||, but they have lower precedence than the assignment operator =. That means PHP performs the assignment first:

PHP Why and and or break assignments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is bool(true), bool(false), bool(false), bool(false). The first line is read as ($x = true) and false: $x gets true, and the and false part is evaluated and thrown away. Likewise $hasAccess = false or true stores false. Only &&, || or explicit parentheses give the result you intended.

You'll find or in older code in this idiom, which relies on the low precedence:

PHP
$file = fopen('data.txt', 'r') or die('Cannot open file');

It means "assign the result of fopen(), and if that's falsy, stop the script". It works, but modern code handles failures with explicit checks or exceptions instead (see Reading and Writing Files and Exceptions).

Use &&, || and ! everywhere. The word forms add nothing except a precedence trap, and code-style tools such as PHP-CS-Fixer have a rule that rewrites and and or to && and ||. For "exactly one of two", where you'd need xor, $a !== $b with two booleans reads just as well and has normal precedence.

Precedence among logical operators

! binds tightest, then &&, then ||. So $a || $b && $c means $a || ($b && $c):

PHP
var_dump(true || false && false);    // bool(true):  true || (false && false)
var_dump((true || false) && false);  // bool(false)

Mixing && and || without parentheses is legal, but readers have to stop and think. Add parentheses whenever both appear, or split the condition into well-named variables:

PHP
$isStaff = $role === 'admin' || $role === 'editor';
$isOwner = $post['authorId'] === $userId;
$canEdit = ($isStaff || $isOwner) && !$post['locked'];

Named intermediate booleans like $isStaff document why a condition exists, and they make debugging easier because you can var_dump() each part. The full precedence table of every PHP operator is in Bitwise, String, Array and Pipe Operators, and conditions get put to work in if, elseif and else.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does var_dump('apple' && 'banana'); print?

    PHP's logical operators always return a boolean. Both strings are truthy, so the result is true. (JavaScript would return 'banana'.)
  2. 2. $ok = false or true; What is $ok?

    or has lower precedence than =, so this is ($ok = false) or true. Use || to get true.
  3. 3. In exists($id) && load($id), when is load() called?

    With &&, PHP skips the right operand when the left one is false, because the result is already known. This is short-circuit evaluation.
  4. 4. Which expression is equivalent to !($isMember || $hasCoupon)?

    De Morgan's law: not (A or B) equals (not A) and (not B). The customer is neither a member nor has a coupon.
  5. 5. What does var_dump(true || false && false); print?

    && binds tighter than ||, so this is true || (false && false), which is true. Use parentheses when you mix the two.

Summary

  • && is true when both sides are true, || when at least one is, ! negates, and xor is true when exactly one side is.
  • Logical operators always return bool. For defaults, use ?: or ??, not ||.
  • Short-circuit evaluation: && skips its right side when the left is false, || when the left is true. Use it for guard conditions and put cheap checks first.
  • ! binds tighter than comparisons: write !($a > $b) or, better, $a <= $b. Use De Morgan's laws to remove negated groups.
  • and, or and xor have lower precedence than =, so $x = true and false stores true. Always use &&, || and !.
  • ! binds tighter than &&, which binds tighter than ||. Add parentheses or named booleans when mixing them.

Next: Null Coalescing, Ternary and Nullsafe Operators