Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP operator difference && and "and" [duplicate]

Tags:

php

Possible Duplicate:
'AND' vs '&&' as operator

Sorry for very basic question but I started learning PHP just a week ago & couldn't find an answer to this question on google/stackoverflow.

I went through below program:

$one = true;
$two = null;
$a = isset($one) && isset($two);
$b = isset($one) and isset($two);

echo $a.'<br>';
echo $b;

Its output is:

false
true

I read &&/and are same. How is the result different for both of them? Can someone tell the real reason please?

like image 374
Kaps Avatar asked Sep 04 '12 17:09

Kaps


People also ask

What is difference between == and === operator in PHP?

== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.

What is the difference between -> and => in PHP?

-> and => are both operators. The difference is that => is the assign operator that is used while creating an array. Thanks. It Helped.

What are PHP comparison operators?

Description. In PHP, comparison operators take simple values (numbers or strings) as arguments and evaluate to either TRUE or FALSE.


2 Answers

The reason is operator precedence. Among three operators you used &&, and & =, precedence order is

  • &&
  • =
  • and

So $a in your program calculated as expected but for $b, statement $b = isset($one) was calculated first, giving unexpected result. It can be fixed as follow.

$b = (isset($one) and isset($two));
like image 58
Kapil Sharma Avatar answered Oct 03 '22 02:10

Kapil Sharma


Thats how the grouping of operator takes place

$one = true;
$two = null;
$a = (isset($one) && isset($two));
($b = isset($one)) and isset($two);

echo $a.'<br>';
echo $b;

Thats why its returning false for first and true for second.

like image 21
Tarun Avatar answered Oct 03 '22 00:10

Tarun