Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

styles

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.

like image 640
Sean Anderson Avatar asked Dec 02 '25 23:12

Sean Anderson


2 Answers

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()?

like image 110
Bogdan Avatar answered Dec 04 '25 13:12

Bogdan


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

like image 31
bugwheels94 Avatar answered Dec 04 '25 13:12

bugwheels94



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!