Using & as a comparison operator??

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Parrot
New php-forum User
New php-forum User
Posts: 9
Joined: Mon Oct 01, 2012 10:17 pm

Using & as a comparison operator??

Postby Parrot » Sun Mar 10, 2013 3:20 pm

I came across this code that kind of confused me:

Code: Select all

if ($strength & 1)


I've never heard of using & as a comparison operator. I've looked up comparison operators in the PHP manual and it doesn't list it as one. But apparently this code runs perfectly well. What is it doing? What's the purpose of using & as a comparison operator?

seandisanti
php-forum Fan User
php-forum Fan User
Posts: 838
Joined: Mon Oct 01, 2012 12:32 pm

Re: Using & as a comparison operator??

Postby seandisanti » Mon Mar 11, 2013 7:56 am

That is one of the bitwise operators supported by php, documented at http://php.net/manual/en/language.operators.bitwise.php

The ampersand is a bitwise AND. basically it looks at the binary representations of the operands, and returns true if one is contained in the other. In the example you've given, I'm assuming $strength is either a boolean value that is currently set to true, or it's an odd number. here's a drawn out example assuming the latter.

if $strength contained the number 33...
$strength's binary representation would be 100001 a bitwise and of that and 1 (000001) shows that they both have 1 in the 2^0 spot.

There are more examples in the manual, and I found an old example I gave someone on another forum forever ago on bitwise 'or' operations.
http://www.autoitscript.com/forum/topic ... l__bitwise


Return to “PHP coding => General”

Who is online

Users browsing this forum: krotbacca and 1 guest

cron