Logical Operators


There's more to the story than just the comparison operators, however. For example, what if you wanted to make sure the temperature was above 75 and below 80? You might do this by using nested if statements:

 temperature = 76; if ($temperature > 75) {     if ($temperature < 80) {         echo "We're in the comfort zone.";     } } 

There's a simpler way, though. You can use the && logical And operator to connect the conditions $temperature > 75 and $temperature < 80 together so that both must be true for the if statement to execute its internal statement. Here's what this looks like:

 <?php     $temperature = 76;     if ($temperature > 75 && $temperature < 80) {         echo "We're in the comfort zone.";     } ?> 

Here, we're connecting the conditions $temperature > 75 and $temperature < 80 using the && operator, and both of them have to be true for the resulting overall expression to be true. You can see the complete list of the PHP logical operators in Table 2-4.

Table 2-4. The Logical Operators

Operator

Operation

Example

Result

and

And

$a and $b

trUE if both $a and $b are TRUE.

or

Or

$a or $b

trUE if either $a or $b is trUE.

xor

Xor

$a xor $b

TRUE if either $a or $b is trUE, but not both.

!

Not

! $a

trUE if $a is not TRUE.

&&

And

$a && $b

trUE if both $a and $b are trUE.

||

 

Or

$a || $b

TRUE if either $a or $b is TRUE.


NOTE

Why are there two And operators and two Or operators? The && and || operators have higher precedence than the and and or operators; see Table 2-1.




    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

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