Section 6.7. Logical Operators


6.7. 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 $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


There are two operators for logical AND and two for logical ORthis 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 function only if the first function returns false.

PHP uses conditional statement short-circuiting, which is a fancy way of saying, "If you write code that says A or B must be true, and PHP finds A to be true, it will not bother evaluating B because the condition is already satisfied." You can use OR very successfully with function calls so that PHP will attempt to run the first function, and, if that function returns false, PHP will run the second function.



PHP in a Nutshell
Ubuntu Unleashed
ISBN: 596100671
EAN: 2147483647
Year: 2003
Pages: 249

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net