运算符
在线手册:中文 英文
PHP手册

逻辑运算符

逻辑运算符
例子 名称 结果
$a and $b And(逻辑与) TRUE,如果 $a 与 $b 都为 TRUE
$a or $b Or(逻辑或) TRUE,如果 $a 或 $b 任一为 TRUE
$a xor $b Xor(逻辑异或) TRUE,如果 $a 或 $b 任一为 TRUE,但不同时是。
! $a Not(逻辑非) TRUE,如果 $a 不为 TRUE
$a && $b And(逻辑与) TRUE,如果 $a 与 $b 都为 TRUE
$a || $b Or(逻辑或) TRUE,如果 $a 或 $b 任一为 TRUE

“与”和“或”有两种不同形式运算符的原因是它们运算的优先级不同(见运算符优先级)。

Example #1 逻辑运算符示例

<?php

// 下面的 foo() 不会被调用,因为它们被运算符“短路”了。
$a = (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());

// "||" 的优先级比 "or" 高
$e false || true// $e 被赋值为 (false || true),结果为 true
$f false or true// $f 被赋值为 false [Altair注:"=" 的优先级比 "or" 高]
var_dump($e$f);

// "&&" 的优先级比 "and" 高
$g true && false// $g 被赋值为 (true && false),结果为 false
$h true and false// $h 被赋值为 true [Altair注:"=" 的优先级比 "and" 高]
var_dump($g$h);
?>

以上例程的输出类似于:

bool(true)
bool(false)
bool(false)
bool(true)

运算符
在线手册:中文 英文
PHP手册
PHP手册 - N: 逻辑运算符

用户评论:

snorrra at gmail dot com (21-Mar-2012 05:48)

Re brad at bradleyproctor dot com

if ($foo) {
   $foo = 5;
}

Can't be replaced with
$foo or $foo = 5;

But it can be replaced with
$foo and $foo = 5;

Anonymous (13-Feb-2012 04:57)

Regarding [ctulek at gmail dot com 18-Oct-2010 02:07] not dangerous if you use the === operator, or understand PHP type juggling; adding to your example:

<?php
$a
= 0;
$b = 'G';
$c = false;

// 3 lines added ...
var_dump((int) 'G');  // => 0
var_dump((bool) 0);   // => false
var_dump((bool) 'G'); // => true

echo ($a == $b) ? "true\n" : "false\n"; // 0 == 0         => true
echo ($a == $c) ? "true\n" : "false\n"; // false == false => true
echo ($c == $b) ? "true\n" : "false\n"; // false == true  => false

// 3 lines added ...
echo ($a === $b) ? "true\n" : "false\n"; // => false
echo ($a === $c) ? "true\n" : "false\n"; // => false
echo ($c === $b) ? "true\n" : "false\n"; // => false
?>

brad at bradleyproctor dot com (25-Oct-2011 08:03)

A handy way to set a variable using or

<?php
if ($foo) {
  
$foo = 5;
}

// Can be replaced with
$foo or $foo = 5;

?>

I use this often for setting variables in functions with optional parameters.

<?php

function foobar($a = null, $b = null) {
  
$a or $a = 10;
  
$b or $b = 20;
  
//...
}

ctulek at gmail dot com (18-Oct-2010 10:07)

Try this...

$a = 0;
$b = 'G';
$c = false;
echo $a == $b ? "true\n" : "false\n";
echo $a == $c ? "true\n" : "false\n";
echo $c == $b ? "true\n" : "false\n";

Output:
true
true
false

Very dangerous...

Rob (23-Oct-2009 06:16)

Another example that might help.

<?php
(isset($panelemail) && !empty($panelemail) ? $panelemail : $userdata['email']);
?>
returns the userdata email address, but this

<?php
(isset($panelemail) AND !empty($panelemail) ? $panelemail : $userdata['email']);
?>
returns false.

The reason is that the two types of ands have a different order of precedence.  "&&" is higher than "AND", and the "?:" operator just happens to come between the two.  Also, since "||" (or) is actually higher than "AND," you should never mix &&s and ||s with ANDs and ORs without paretheses.

For example:

<?php
     true
&& false || false
?>
returns false, but

<?php
     true
AND false || false
?>
returns true.

daevid at daevid dot com (11-Aug-2009 02:33)

If you ever need to alternate row colors for data output in a table, do this:

in your CSS put these two classes:
    .dataRow1 { background-color: #DFDFDF; }
    .dataRow2 { background-color: #FFFFFF; }

then in your PHP, loop over each row:

<?php
// ....
foreach ($foo_array as $foo) {
  
?><tr class="<?php echo ($dr = !$dr) ? "dataRow1" : "dataRow2"; ?>"><td><?php echo $foo
?>
</td></tr><?php
}
?>

No need to initialize $dr as by default PHP will make it a boolean "false", then each iteration, it will toggle true/false and substitute the CSS class

momrom at freenet dot de (19-Apr-2009 04:32)

Evaluation of logical expressions is stopped as soon as the result is known.
If you don't want this, you can replace the and-operator by min() and the or-operator by max().

<?php
function a($x) { echo 'Expression '; return $x; }
function
b($x) { echo 'is '; return $x; }
function
c($x) { echo $x ? 'true.' : 'false.' ;}

c( a( false ) and b( true ) ); // Output: Expression false.
c( min( a( false ), b( true ) ) ); // Output: Expression is false.

c( a( true ) or b( true ) ); // Output: Expression true.
c( max( a( true ), b( true ) ) ); // Output: Expression is true.
?>

This way, values aren't automaticaly converted to boolean like it would be done when using and or or. Therefore, if you aren't sure the values are already boolean, you have to convert them 'by hand':

<?php
c
( min( (bool) a( false ), (bool) b( true ) ) );
?>

sandaimespaceman at gmail dot com (12-Sep-2008 04:07)

There's one userful way to use the or operator:

<?php
//If the connection was success, "Connected to database" will be shown.
//If the connection was failed, "Unable to connect" will be shown.(NOTE: The @ will hide error messages)
@mysql_connect("localhost", "root", "password") or die("Unable to connect");
echo
"Connected to database";
?>

So you don't need to use if operators to add more lines.

jeffjeffleelee at hotmail dot com (07-Jul-2008 05:30)

@zhustar:

I will verify the following:

<?php
$a
= false xor true;
var_dump($a);  // bool(false)

$a = (false xor true);
var_dump($a);  // bool(true)
?>

At first I thought this was some egregious bug, and then I realized that this is merely an issue of operator precedence. English-word boolean operators have relatively low precedence--in fact they take place after assignment. So the first example assigns false to $a, and then does an xor operation on $a and boolean true.

loaded67 at hotmail dot com (12-Jun-2008 06:40)

Someone ever noted that C type operators are applicable in php as well?
more like a (bool / boolean) cast...

See:

<?php
ini_set
('display_errors', 1);
ini_set('error_reporting', 8191);// php5

$whatever = NULL;
$Iwaslike = 'WTF!';

if(!!(
$whatever)){
    echo
'$whatever'.PHP_EOL;
}
if(!!(
$Iwaslike)){
    echo
'$Iwaslike'.PHP_EOL;
}
if(!!!(
$whatever)){
    echo
'$whatever'.PHP_EOL;
}
if(!!!(
$Iwaslike)){
    echo
'$Iwaslike'.PHP_EOL;
}
?>

momrom at freenet dot de (12-Jun-2008 03:10)

Some examples from the english manual that aren't avaiable in all languages:

Like in C, logical expressions are evaluated
from left to right until the result is known.
foo() will never get called in the following cases.
<?php
$a
= (false && foo());
$b = (true  || foo());
$c = (false and foo());
$d = (true  or  foo());
?>

"||" has a greater precedence than "="
which has a greater one than "or"
<?php
// same as ($e = (false || true)),
// expression is true and $e ist assigned to true
$e = false || true;

// same as (($e = false) or true),
// expression is true but $e is assigned to false
$f = false or true;
?>

"&&" has a greater precedence than "="
which has a greater one than "and"
<?php
// same as ($e = (true || false)),
// expression is false and $e ist assigned to false
$g = true && false;

// same as (($e = true) and false),
// expression is false but $e is assigned to true
$h = true and false;
?>

Benjamin (29-Feb-2008 05:48)

Re:Richard

I show $b printing 1 rather than "banana". Here's how I understand what's going on.

<?php
//"||" has a greater precedence than "or"

$a=0 or $a="avocado"; //evaluated as ($a=0) or ($a="avacado")
//Since $a=0 is false, $a="avocado" is evaluated and $a is assigned the string value "avocado".
echo "$a"; //prints "avocado"
var_dump ($a); // string(7) "avocado"

$b=0 || $b="banana"; // evaluated as $b = (0 || $b = "banana")
echo $b; //prints "1"
var_dump ($b); // bool(true)
?>

Richard (31-Jan-2008 02:22)

Re Lawrence:

You sort of can do conditional evaluation:

$a=0 or $a="avocado";
echo "$a";                              #Prints "avocado"

But oddly:

$b=0 || $b="banana";
echo $b;                                 #Prints "banana"

zhustar at gmail dot com (18-Jan-2008 03:02)

$a = false xor true;
var_dump($a);  // bool(false)

$a = (false xor true);
var_dump($a);  // bool(true)

pepesantillan at gmail dot com (23-Dec-2007 11:23)

worth reading for people learning about php and programming: (adding extras <?php ?> to get highlighted code)

about the following example in this page manual:
Example#1 Logical operators illustrated

...
<?php
// "||" has a greater precedence than "or"
$e = false || true; // $e will be assigned to (false || true) which is true
$f = false or true; // $f will be assigned to false
var_dump($e, $f);

// "&&" has a greater precedence than "and"
$g = true && false; // $g will be assigned to (true && false) which is false
$h = true and false; // $h will be assigned to true
var_dump($g, $h);
?>
_______________________________________________end of my quote...

If necessary, I wanted to give further explanation on this and say that when we write:
$f = false or true; // $f will be assigned to false
the explanation:

"||" has a greater precedence than "or"

its true. But a more acurate one would be

"||" has greater precedence than "or" and than "=", whereas "or" doesnt have greater precedence than "=", so

<?php
$f
= false or true;

//is like writting

($f = false ) or true;

//and

$e = false || true;

is the same as

$e = (false || true);

?>

same goes for "&&" and "AND".

If you find it hard to remember operators precedence you can always use parenthesys - "(" and ")". And even if you get to learn it remember that being a good programmer is not showing you can do code with fewer words. The point of being a good programmer is writting code that is easy to understand (comment your code when necessary!), easy to maintain and with high efficiency, among other things.

paranoiq at centrum dot cz (19-Nov-2007 04:00)

and, or and xor can be used as conditional constructs:

<?php
// do_that() is executed only if do_this() returns false
if($something) do_this() or do_that();
// $b is assigned to $b, do_that() is executed if $b is false
if($something) $a = $b or do_that();

// do_that() is executed only if do_this() returns true
if($something) do_this() and do_that();
// $b is assigned to $b, do_that() is executed if $b is true
if($something) $a = $b and do_that();

// both do_that() and do_this() are executed..
if($something) do_this() xor do_that();
// .. so the behaviour is same as:
if($something) {
   
do_this();
   
do_that();
}
?>

for understanding what happens if $b is NULL or do_this() returns NULL, read the avbentem's comment on NULL type. generaly speaking, NULL is threated like false in most cases.

peter dot kutak at NOSPAM dot gmail dot com (01-Oct-2007 08:36)

$test = true and false;     ---> $test === true
$test = (true and false);  ---> $test === false
$test = true && false;      ---> $test === false

Lawrence (28-Aug-2007 08:04)

Note that PHP's boolean operators *always* return a boolean value... as opposed to other languages that return the value of the last evaluated expression.

For example:

$a = 0 || 'avacado';
print "A: $a\n";

will print:

A: 1

in PHP -- as opposed to printing "A: avacado" as it would in a language like Perl or JavaScript.

This means you can't use the '||' operator to set a default value:

$a = $fruit || 'apple';

instead, you have to use the '?:' operator:

$a = ($fruit ? $fruit : 'apple');

Andrew (13-Aug-2007 04:49)

> <?php
> your_function() or return "whatever";
>
?>

doesn't work because return is not an expression, it's a statement. if return was a function it'd work fine. :/

looris at gmail dot com (18-Jun-2007 03:46)

Please note that while you can do things like:
<?php
your_function
() or die("horribly");
?>

you can't do:
<?php
your_function
() or return "whatever";
?>
(it will give you a syntax error).

eduardofleury at uol dot com dot br (14-Jun-2007 02:16)

;;;;;;;;;;;;;;;;;;;;;;;;;
; P1 P2; And; OR  ; XOR ;
;;;;;;;;;;;;;;;;;;;;;;;;;
; V  V ; V  ; V   ; F   ;
; V  F ; F  ; V   ; V   ;
; F  V ; F  ; V   ; V   ;
; F  F ; F  ; F   ; F   ;
;;;;;;;;;;;;;;;;;;;;;;;;;

<?php

$a
= 2;
$b = 3;
$c = 6;

print !(
$a > $b && $b < $c);// true

print (($a > $b) and ($b < $c));// false

print ($a == $b or $b < $c); // true

print $a == $b || $b < $c; // true

$x = $a < $b; //$x = true

$y = $b === $c; //$y = false

print  $x xor $y; // true

?>