0

Is anybody able to exlain this behaviour:

<?php

$var1 = true;

$var2 = 0;

$var3 = $var1 AND $var2;

var_export($var3); // Output: true

var_export(true AND 0); // Output: false    

var_export($var1 AND $var2); // Output: false

Output comes from PHP 7.0

Why is the first output true while the 3rd output is false?

By the way: it doesnt matter if $var2 is 0 or false. The behaviour is the same.

@all: I know that I SHOULD use && and I always do!

steven
  • 4,868
  • 2
  • 28
  • 58

2 Answers2

5

It actually comes because && is different from AND.

$var1 = true;
$var2 = 0;

$var3 = $var1 && $var2;
var_export($var3); // Output: false

$var3 = $var1 AND $var2;
var_export($var3); // Output: true

In the && case you actually write $var3 = ( $var1 && $var2 )

In the AND case you actually write ( $var3 = $var1 ) AND $var2

That's because = has greater precedence then AND, but && has greater precedence then =

Michel
  • 4,076
  • 4
  • 34
  • 52
2

It's because of your use of AND - see here for full docs

but in short:

$a and $b | And | TRUE if both $a and $b are TRUE.

Now let's take your code:

$var1 = true; # this is true
$var2 = 0; # this is false
$var3 = $var1 && $var2; # this will be false as $var2 is false

var_export($var3); # my machine shows false
var_export(true && 0); # this shows false as expected, 0 == false
var_export($var1 && $var2); # $var2 is false. This shows false

Edit

The real reason is that && has higher predence - which is why the above code does what I originally thought it should do with using AND. This is not the case, see here:

$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);

# outputs:
# bool(false)
# bool(true)

So your code is doing as expected, just in a different way to how I first thought.

treyBake
  • 6,440
  • 6
  • 26
  • 57