Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Operators

PHP logical operators

Reference for PHP logical operators: &&, ||, !, and, or, xor, short-circuit evaluation and the precedence trap between && and the word 'and'.

Logical operators combine boolean conditions. && (and), || (or) and ! (not) are the everyday forms. The word forms and, or and xor do the same job (xor has no symbol form) but have a much lower precedence, which matters when you assign the result.

&& and || short-circuit: the right side runs only if it can change the result. Every logical operator converts its operands to booleans and returns a real true or false.

PHP
if ($age >= 18 && $hasTicket) { /* ... */ }

Try it

PHP Short-circuit evaluation

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.

PHP The precedence trap with and / or

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.

Syntax

PHP
$a && $b    $a and $b
$a || $b    $a or $b
!$a
$a xor $b
Operator Result
&&, and true if both operands are truthy
||, or true if at least one operand is truthy
xor true if exactly one operand is truthy (never short-circuits)
! true if the operand is falsy

Usage notes

  • Precedence. && and || bind tighter than =. The words and and or bind looser than =, so $b = true and false assigns true to $b. Use the symbols, or add parentheses.
  • Falsy values. false, 0, 0.0, "", "0", [] and null are falsy. Everything else is truthy, including "0.0" and "false".
  • Return type. Unlike JavaScript or Python, $a || $b returns a boolean, not one of the operands. Use ?: or ?? to pick a value.
  • Guards. $x !== null && $x->method() is the standard way to avoid errors; see also the nullsafe operator.
  • Side effects. Do not rely on the right side running. If you need both sides evaluated, compute them first.
  • or die() is an old idiom (fopen(...) or die("x")). Prefer exceptions.
  • ! binds tightly. !$a == $b means (!$a) == $b.