-2
$A = True;
$B = False;
$C = $A AND $B;
$D = $A && $B;

echo 'C='.$C.'<br/>';
echo 'D='.$D.'<br/>';

Output:
C=1
D=

Or I missing something?

henry
  • 27
  • 4
  • They also have different precedences. Check the [documentation page](http://php.net/manual/en/language.operators.precedence.php) – axiac Jan 09 '15 at 09:57

5 Answers5

7

AND has lower precedence.

$C = $A AND $B will be parsed as ($C = $A) AND $B.

knittl
  • 246,190
  • 53
  • 318
  • 364
1

For variables $a and $b set as follows:

<?php

$a = 7;
$b = 0;

the advantage of using AND is short-circuit evaluation that occurs in code like the following:

$c = $a AND $b;
var_dump( $c ); // 7

Since the assignment operator has higher precedence than AND, the value of $a gets assigned to $c; $b gets skipped over.

Consider the following code in contrast:

<?php

$c = $a && $b;
var_dump( $c ); // (bool) false

In this snippet, && has a higher precedence than the assignment operator, and given the value of $a being non-zero, there is no short-circuiting. The result of this logical AND is based on the evaluation of both $a and $b. $a evaluates as true and $b as false. The overall value of the expression, false, is what gets assigned to $c. This result is quite different than in the prior example.

slevy1
  • 3,797
  • 2
  • 27
  • 33
  • Okay I see. I didn't see asignment operator included in short-circuiting. Thank you for all that answered, the case is closed. – henry Jan 12 '15 at 03:08
0

both have same thing, but && has higher precedence than AND.

for more:- 'AND' vs '&&' as operator

Community
  • 1
  • 1
Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44
0

If you want to test logic values use var_dump(). Like this:

$a = true;
$b = false;

echo '<pre>';
var_dump($a AND $b);
echo PHP_EOL;
var_dump($a && $b);
echo '</pre>'
Forien
  • 2,712
  • 2
  • 13
  • 30
-1

D is the correct output.

PHP doesn't echo false values, but if you did var_dump($D); then you should see that the value is false.

You should use && when trying to do boolean operations.

Varedis
  • 738
  • 5
  • 14
  • You can't assing vardup with concatenation to strings. It returns nothing. – Forien Jan 09 '15 at 09:58
  • Corrected, one of those stupid things that we forget. It still printed, it was just out of order. – Varedis Jan 09 '15 at 10:03
  • PHP _does_ echo falsy values, you just don't see it. If `false` (or `null`) are converted to a string, the result is an empty string (`var_dump((string) false);`) – Elias Van Ootegem Jan 09 '15 at 10:17
  • @ Elias Van Ootegem actually PHP prints nothing at all when false is in a string context. Internally PHP optimizes away the empty strings by having the function responsible for creating printable output return 0 when an empty string results; see http://lxr.php.net/xref/PHP_5_6/Zend/zend.c#322 – slevy1 Jan 09 '15 at 11:40