Do I need parenthesises?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
SmokyBarnable
Forum Contributor
Posts: 105
Joined: Wed Nov 01, 2006 5:44 pm

Do I need parenthesises?

Post by SmokyBarnable »

This seems to work fine but I was wondering if I should use parenthesises?

Code: Select all

if ($hours===1&&$minutes<30)
or

Code: Select all

if (($hours===1)&&($minutes<30))
Thanks.
User avatar
aaronhall
DevNet Resident
Posts: 1040
Joined: Tue Aug 13, 2002 5:10 pm
Location: Back in Phoenix, missing the microbrews
Contact:

Post by aaronhall »

The extra parentheses affect only the order of operations (in this case, not at all) -- they aren't syntactically required
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

For readability..

Code: Select all

if (($hours === 1) && ($minutes < 30))
{
    // blah blah
    // blah
}
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

This is too simple, you don't need them.
lanasa
Forum Newbie
Posts: 14
Joined: Mon Mar 26, 2007 7:49 am
Location: Buffalo, NY

Re: Do I need parenthesises?

Post by lanasa »

The reason you don't need them is the '&&' operator has more precidence than the < or === operators.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

&& has a lower precedence, not higher.

I prefer to use the "and," "or" and "xor" keywords more than the "&&" and "||" operators because they have an even lower precedence. When I need to take the operation up a bit in the precedence, then I use the symbolic logicals.

http://php.net/language.operators#langu ... precedence
bubblenut
Forum Newbie
Posts: 20
Joined: Sat Feb 03, 2007 4:16 am
Location: London

Post by bubblenut »

To add to feyds point on using keywords, take the following example.

Code: Select all

$val1 = 1; $val2 = 2;
if( $val1 = $val2 && true ) {}

var_dump( $val1 );
You will notice that $val1 is bool(true) rather than int(2). This is because the precedence of = is lower than that of && so effectively the statement is this

Code: Select all

$val1 = ($val2 && true)
however, when using keywords instead the precedence of = is higher. With the following example you will notice that the result is int(2)

Code: Select all

$val1 = 1; $val2 = 2;
if( $val1 = $val2 and true ) {}

var_dump( $val1 );
[edit]I spell like a 2 year old[/edit]
Post Reply