Igor Parra
Igor Parra

Reputation: 10348

Precedence of AND and OR into an IF statement

Are equivalents these statements?

if ($a || $b && $c)
{
    // ...
}

if (($a || $b) && $c)
{
    // ...
}

EDIT

What a beating! But worth it... THX to all!

Upvotes: 0

Views: 2345

Answers (5)

Joseph Silber
Joseph Silber

Reputation: 219920

Answer: NO. They're not equivalent.

Check out the PHP Operator Precedence table. It clearly lists && before ||.

See it here in action: http://viper-7.com/cPycas


If you want to use precedence instead of parenthesis, you can use the more verbose AND:

if ($a || $b AND $c)
{
    // ...
}

Here's the demo, but I'd advise you against it, since it's not as clear as parenthesis.

Upvotes: 2

StuartLC
StuartLC

Reputation: 107237

&& has precedence over ||. Operator precedence

Upvotes: 0

Captain Giraffe
Captain Giraffe

Reputation: 14705

Consider AND as multiplication, OR as addition, you'll get the truthiness as well as the priority.

$a = 1; 
$b = 0;
$c = 0;

if ($a + $b * $c)
{
    // ...
}

if (($a +  $b) * $c)
{
    // ...
}

Upvotes: 1

Bart Kiers
Bart Kiers

Reputation: 170148

No. In PHP, ($a || $b && $c) is evaluated as: ($a || ($b && $c))

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

Upvotes: 1

John
John

Reputation: 16007

The && has higher precedence than the ||, so no, they're not equivalent.

Upvotes: 1

Related Questions