Jongosi
Jongosi

Reputation: 2355

PHP Comparison With Or Without Brackets

Are these two PHP comparisons exactly the same? By that I mean, will the result be the same for both statements; with and without brackets?

Without brackets:

if ( $params['isAjax'] == '1' && $isEnabled == '1' ) {
    ...
}

And with brackets enclosing each statement:

if ( ($params['isAjax'] == '1') && ($isEnabled == '1') ) {
    ...
}

Additionally, which is the better method. Is one superior to another? Thanks.

Upvotes: 2

Views: 229

Answers (2)

ElGavilan
ElGavilan

Reputation: 6904

They are exactly the same. Order of operations dictates that == evaluates before &&.

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

Upvotes: 2

Mic1780
Mic1780

Reputation: 1794

Yes they are logically equal

if ( (true) && (true) )

is the same as

if ( true && true )

grouping statements using () is effective when you want to group logical statements

if ( (true && true) || false ) //true
if ( (true && false) || false ) //false
if ( (true && false) || true ) //true
if ( (true || false) && true ) //true
if ( (true || false) && false ) //false

without grouping these statements would be

if ( true && true || false ) //true
if ( true && false || false ) //false
if ( true && false || true ) //true
if ( true || false && true ) //true
if ( true || false && false ) //true <-- different

Grouping statements make it more readable as well as removes unwanted results (i didnt know ( true || false && false ) was true).

Upvotes: 1

Related Questions