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.
if ($age >= 18 && $hasTicket) { /* ... */ }
Try it
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.
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
$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 wordsandandorbind looser than=, so$b = true and falseassignstrueto$b. Use the symbols, or add parentheses. - Falsy values.
false,0,0.0,"","0",[]andnullare falsy. Everything else is truthy, including"0.0"and"false". - Return type. Unlike JavaScript or Python,
$a || $breturns 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 == $bmeans(!$a) == $b.