Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page