$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?
$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?
AND
has lower precedence.
$C = $A AND $B
will be parsed as ($C = $A) AND $B
.
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.
both have same thing, but &&
has higher precedence than AND.
for more:- 'AND' vs '&&' as operator
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>'
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.