Operators, Conditionals, and PHP Decision-Making - Logical operators
(Page 2 of 4 )
Logical operators work with the Boolean results of relational operators to build more complex logical expressions; there are four logical operators shown in Table 4-3. These operators are also Boolean operators.
Table 4-3. Logical operators
| Logical operator | Meaning |
| AND | TRUE if both operands must be TRUE |
| OR | TRUE if at least one operand is TRUE |
| XOR | TRUE if only one operand is TRUE |
| NOT | TRUE if FALSE , FALSE if TRUE |
Because they have different precedence levels, both AND and OR have two representations. AND can be given a higher precedence level as && , while OR can be given a higher precedence level as ||.
To test whether both operands are true, use the AND operator, also represented as the double ampersands (&&) seen in Table 4-2. Both the double ampersand as well as AND are logical operators; the only difference is that the double ampersand is evaluated before the AND operator. The operators || and OR follow the same rule. TRUE is returned only if both operands are TRUE; otherwise, FALSE is returned. See Table 4-3 for more information.
To test whether one operand is TRUE, use the OR operator, which is also represented as double vertical bars or pipes (||). TRUE is returned only if either or both operands are TRUE.
Using the OR operator can create tricky program logic problems. If PHP finds that the first operand is TRUE, it won't evaluate the second operand. While this saves execution time, you need to be careful that the second operator doesn't contain code that needs to be executed for your program to work properly.
To test whether only one operand is TRUE, use XOR. XOR returns TRUE if one and only one operand is TRUE. It returns FALSE if both operands are TRUE.
To negate a Boolean value, use the NOT operator, represented as an exclamation point (!). It returns TRUE if the operand has a value of FALSE. It returns FALSE if the operand is TRUE.
Table 4-4 displays logical statements and their results.
Table 4-4. Logical statements and their results
Example logical statement | Result |
TRUE AND TRUE | TRUE |
FALSE AND TRUE | FALSE |
TRUE OR FALSE | TRUE |
FALSE OR FALSE | FALSE |
TRUE XOR TRUE | FALSE |
TRUE XOR FALSE | TRUE |
!TRUE | FALSE |
!FALSE | TRUE |
Next: Conditionals >>
More Programming Basics Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the book Learning PHP and MySQL, Second Edition, written by Michele Davis and Jon Phillips (O'Reilly, 2006; ISBN: 0596101104). Check it out today at your favorite bookstore. Buy this book now.
|
|