1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
|
<?xml version="1.0" encoding="utf-8"?>
<sect1 xml:id="language.operators.logical">
<title>Logical Operators</title>
<titleabbrev>Logic</titleabbrev>
<table>
<title>Logical Operators</title>
<tgroup cols="3">
<thead>
<row>
<entry>Example</entry>
<entry>Name</entry>
<entry>Result</entry>
</row>
</thead>
<tbody>
<row>
<entry>$a and $b</entry>
<entry>And</entry>
<entry>&true; if both <varname>$a</varname> and <varname>$b</varname> are &true;.</entry>
</row>
<row>
<entry>$a or $b</entry>
<entry>Or</entry>
<entry>&true; if either <varname>$a</varname> or <varname>$b</varname> is &true;.</entry>
</row>
<row>
<entry>$a xor $b</entry>
<entry>Xor</entry>
<entry>&true; if either <varname>$a</varname> or <varname>$b</varname> is &true;, but not both.</entry>
</row>
<row>
<entry>! $a</entry>
<entry>Not</entry>
<entry>&true; if <varname>$a</varname> is not &true;.</entry>
</row>
<row>
<entry>$a && $b</entry>
<entry>And</entry>
<entry>&true; if both <varname>$a</varname> and <varname>$b</varname> are &true;.</entry>
</row>
<row>
<entry>$a || $b</entry>
<entry>Or</entry>
<entry>&true; if either <varname>$a</varname> or <varname>$b</varname> is &true;.</entry>
</row>
</tbody>
</tgroup>
</table>
<simpara>
The reason for the two different variations of "and" and "or"
operators is that they operate at different precedences. (See
<link linkend="language.operators.precedence">Operator
Precedence</link>.)
</simpara>
<example>
<title>Logical operators illustrated</title>
<programlisting role="php">
<![CDATA[
<?php
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
// --------------------
// "||" has a greater precedence than "or"
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f before the "or" operation occurs
// Acts like: (($f = false) or true)
$f = false or true;
var_dump($e, $f);
// --------------------
// "&&" has a greater precedence than "and"
// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;
// The constant true is assigned to $h before the "and" operation occurs
// Acts like: (($h = true) and false)
$h = true and false;
var_dump($g, $h);
?>
]]>
</programlisting>
&example.outputs.similar;
<screen>
<![CDATA[
bool(true)
bool(false)
bool(false)
bool(true)
]]>
</screen>
</example>
</sect1>
|