Logical Operators
When resolving equations using logic, you can choose from one of six operators, listed in Table 6-7.
Table 6-7. The logical operators
|
AND |
Logical AND |
True if both |
|
&& |
Logical AND |
True if both |
|
OR |
Logical OR |
True if either |
|
|| |
Logical OR |
True if either |
|
XOR |
Logical XOR |
True if either |
|
! |
Logical NOT |
Inverts true to false and false to true: |
There are two operators for logical AND and two for logical OR—this is to facilitate operator precedence in more complicated expressions. The && and || are more commonly used than their AND and OR counterparts because they are executed before the assignment operator, which is usually what you would expect. For example:
$a = $b && $c;
Most people would read that as "set $a to be true if both $b and $c are true," and that is correct. However, if you replace the && 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, one common use for the OR operator involves the die() function, which causes PHP to terminate execution immediately, like this:
do_some_func() OR die("do_some_func() returned false!");In that situation, do_some_func() will be called, and, if it returns false, die() will be called to terminate the script. The reason that code works is because the OR operator tells PHP to execute the second ...