Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

php - whats the difference in parentheses in IF statements?

I've noticed in my dealings with PHP & javascript, still learning btw, that the following seems to produce the same results.

        if( ( $A==0 ) && ( $B==0 ) ){}

        if( $A==0 && $B==0 ){}

What is the proper term for this in programming so I can learn more about it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Parenthesis determine the order in which comparisons are made. Your example is a pretty simple one that doesn't need parenthesis at all, but look at something like this

if ($a == 0 || $b == 0 && $c == 0 || $dd == 0)

This is actually equivalent to

if ($a == 0 || ($b == 0 && $c == 0) || $dd == 0)

because && is evaluated first in PHP as it has a higher precedence than the ||

IN most cases, when you have complex conditionals, you want to make sure to use parenthesis, if not to get the order of operations right, then at least to make it clear to the code reader what you are trying to do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...