Logical Operators in PHP : Tutorial



Logical operators are used to control the flow of PHP script. They are mostly used with if, while, or some other control statement.

Logical operators are binary operators (except NOT (!)).

List of Logical Operators

Operator   Syntax		Result
==========================================================================
AND       $op1 and $op2		TRUE if both $op1 and $op2 are TRUE.
OR        $op1 or  $op2		TRUE if either $op1 or $op2 is TRUE.
XOR       $op1 xor $op2		TRUE if either $op1 or $op2 is TRUE, but not both.
NOT       !$op			TRUE if $op is not TRUE.
AND       $op1 &&  $op2		TRUE if both $op1 and $op2 are TRUE.
OR        $op1 ||  $op2		TRUE if either $op1 or $op2 is TRUE.


Example 1: Logical AND Operator
<?php

$a = 10;

$b = 20;

var_dump($a>5 AND $b>5);

var_dump($a && $b);

?>
Output

bool(true) bool(true)


Example 2: Logical OR Operator
<?php

$a = 10;

$b = 20;

var_dump($a>30 OR $b>30);

var_dump($a || $b);

?>
Output

bool(false) bool(false)


Example 3: Logical NOT Operator
<?php

$a = 10;

var_dump(!($a>5));

?>
Output

bool(false)


Example 4: Logical XOR Operator
<?php

$a = 10;
$b = 20;

$c = 40;
$d = 50;

var_dump($a>5 XOR $b>5);

var_dump($c>5 XOR $c>70);

?>
Output

bool(false) bool(true)


PHP boolean operators always return a boolean value.
|| has a greater precedence than OR
&& has a greater precedence than AND