Proper use of parentheses in if with and/or statements PHP

1.8k views Asked by At

This is kind of a ridiculous question...mostly to hopefully prove my old man programmer friend wrong.

I write if statements like this (ones with AND/OR in them), as I have always known...

if($something == $something OR $whatever == $whatever){stuff...}

My old man friend does this...

if(($something == $something) OR ($whatever == $whatever)){stuff...}

I have never seen anyone do it like that before. It does run without error. I told him that is invalid code but he shrugs it off and says it runs. Is it valid? I mean...it does run. Extra characters so mine still wins. Was this an old way of doing it in PHP? I can't find any info on the latter style. Just kind of curios. Thanks.

4

There are 4 answers

0
Bogdan On

Both are valid ways, the second one, with the extra parentheses is more readable.

Why use an extra set of parenthesis when using PHP boolean test in an IF()?

0
bugwheels94 On

Parenthesis are also called grouping operators which are used so that expressions with lower precedence can be evaluated before an expression with higher priority.

Inside if statement expression is needed which is parsed depending upon the precedence of the operators using some algorithm like Shunting Yard.

So it does not matter how many grouping operator you add to some expression which is already guaranteed to be evaluated before other binary operators( OR in your case)

For eg. 4*3 + 5 is same as (4*3) + 5( as * has higher priority and will be evaluated before)

Acc. to shunting yard your postfix expression is

$something $something == $whatever $whatever == OR

and your old friends postfix is also

$something $something == $whatever $whatever == OR

Only difference is yours is micro faster while his one's is probably more readable

0
glennw On

The old man's method is not incorrect. It can be written both ways. That is due to the fact that you can evaluate a complex boolean expression all the way down to true or false which is all that is required. If someone said write this expression with as few parenthesis as possible, then your method would be "right".

1
Matt Clark On

That is completely valid, and some may argue that parenthesis are better for ease of readability, however there is no right way.

What if you had three... :O

syntactically, something in this format

if ( a == b OR a == c OR a == d )

could be completely different than something in this format

if ( a == b OR ( a == c OR a == d ) )
if ( ( a == b OR a == c ) OR a == d )