PHP Logical Operators
Description
We can use logical operators to combine boolean value and do the boolean logic arithmetic.
PHP Logical Operators
When resolving equations using logic, you can choose from one of six operators, listed in the following table.
Operator | Name | Meaning |
---|---|---|
AND | Logical AND | True if both $a and $b are true |
&& | Logical AND | True if both $a and $b are true |
OR | Logical OR | True if either $a or $b is true |
|| | Logical OR | True if either $a or $b is true |
XOR | Logical XOR | True if either $a or $b is true, but not both |
! | Logical NOT | Inverts true to false and false to true: !$a |
Boolean values to produce a result of either true or false :
Operator | Example | Result |
---|---|---|
&&(and) | $x && $y | true if both $x and $y evaluate to true ; false otherwise |
and | $x and $y | true if both $x and $y evaluate to true ; false otherwise |
|| (or) | $x || $y | true if either $x or $y evaluates to true ; false otherwise |
or | $x or $y | true if either $x or $y evaluates to true ; false otherwise |
xor | $x xor $y | true if $x or $y (but not both) evaluates to true ; false otherwise |
! (not) | !$x | true if $x is false ; false if $x is true |
Here are some simple examples of logical operators in action:
<?PHP//from w ww . j av a 2 s . c o m
$x = 2;
$y = 3;
echo ( ($x > 1) && ($x < 5) ) . "\n";
echo ( ($x == 2) or ($y == 0) ) . "\n";
echo ( ($x == 2) xor ($y == 3) ) . "\n";
echo ( !($x == 5 ) ) . "\n";
?>
The code above generates the following result.
The && and || are more commonly used than their AND and OR counterparts because they are executed before the assignment operator. For example:
$a = $b && $c;
The code above says "set $a to be true if both $b and $c are true.". But, if the && is replaced with AND, the assignment operator is executed first, which makes PHP read the expression like this:
($a = $b) AND $c;
This is sometimes the desired behavior. For example in the following statement.
do_some_func() OR die("do_some_func() returned false!");
In code above, do_some_func() will be called, and, if it returns false, die() will be called to terminate the script. The OR operator tells PHP to execute the second function only if the first function returns false.
PHP uses conditional statement short-circuiting.
It reads "A or B must be true, and PHP finds A to be true, it
will not evaluate B since the condition is satisfied."
The same theory applies to and
.
False value
In addition, PHP considers the following values to be false :
- The literal value false
- The integer zero (0)
- The float zero ( 0.0 )
- An empty string ( " " )
- The string zero ( "0" )
- An array with zero elements
- The special type null (including any unset variables)
- A SimpleXML object that is created from an empty XML tag
All other values are considered true in a Boolean context.