Using & as a comparison operator??

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

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

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?

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

Mon Mar 11, 2013 7:56 am

That is one of the bitwise operators supported by php, documented at

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. ... l__bitwise

New php-forum User
New php-forum User
Posts: 21
Joined: Tue Oct 27, 2015 6:05 am

Tue Oct 27, 2015 7:01 am

It is acting as bitwise operator in your code. It is used to check bit wise equivalency.

Post Reply