2

I tried the following code and got && and and are different.

<?php

$keyWord =  2 and 3>4;

$symbol  =  2 &&  3>4;

echo $keyWord===$symbol ? 'equal' : 'not-equal';

output: not-equal

why?

Mohammed H
  • 6,880
  • 16
  • 81
  • 127

3 Answers3

9

They do not have the same precedence. Fully parenthesised, your code is:

($keyWord = 2) and (3>4); // $keyWord = 2
$symbol = (2 && (3>4)); // $symbol = false

2 and false are clearly not the same, hence 'not-equal'.

More on operator precedence

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
3

Well, altering the code slightly to:

<?php
$keyWord =  2 and 3>4;

$symbol  =  2 &&  3>4;

var_dump($keyWord);
var_dump($symbol);
?>

produces an output of:

int(2) bool(false)

As Kolink points out above, this is due to operator precedence.

2

Here is the precedence of logical operators (part of the table)

left    &&  logical
left    ||  logical
left    ? :     ternary
right   = += -= *= /= .= %= &= |= ^= <<= >>= =>     assignment
left    and

In your case :

case 1:

$keyWord =  2 and 3>4;

($keyWord =  2) and (3>4);

Here $keyWord = 2

case 2:

$symbol  =  2 &&  3>4;

$symbol  =  (2 && (3>4));

Here $symbol = false

Solution : $keyWord = (2 and (3>4)); and $symbol = 2 && (3>4); Use brackets

Ref: http://php.net/manual/en/language.operators.precedence.php

Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73