Ryan
Ryan

Reputation: 14659

Difference between AND [and] &&

Given the statement:

if($value && array_key_exists($value, $array)) {

         $hello['world'] = $value;

        }

Would it be best to use the logical operator AND as opposed to &&?

Upvotes: 3

Views: 333

Answers (4)

Shef
Shef

Reputation: 45589

They are the same in conditional statements, but be careful on conditional assignments:

// The result of the expression (true && false) is assigned to $g
// Acts like: ($g = (true && false))
$g = true && false;

// The constant true is assigned to $h and then false is ignored
// Acts like: (($h = true) and false)
$h = true and false;

and

// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;

From the Logical Operators manual you linked to.

Upvotes: 3

mysterious
mysterious

Reputation: 1478

only difference of spelling..its a good practice to use && instead of AND or and..

Upvotes: 1

Dennis
Dennis

Reputation: 32608

The link you provide has a note:

The reason for the two different variations of "and" and "or" operators is that they operate at different precedences. (See Operator Precedence.)

In your case, since it's the only operator, it is up to you, but they aren't exactly the same.

Upvotes: 3

theomega
theomega

Reputation: 32051

On their own, they do exactly the same. So a && b means the same than a and b. But, they are not the same, as && has a higher precedence than and. See the docs for further information.

This example here shows the difference:

// The result of the expression (false && true) is assigned to $e
// Acts like: ($e = (false && true))
$e = false && true;

// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) and true)
$f = false and true;

Upvotes: 11

Related Questions