开发者

PHP if statement question (& operator)

I'm using a function I found online. What does the & mean in this co开发者_如何学Cnditional?

if ($strength & 8) { $consonants .= '@#$%'; }

$strength is supposed to be a number 0-8. The function is intending to use all $consonants concatenations where $strength < 8. (might explain why the function is not working).


A single & is the bitwise operator and the double && is the logical. (i.e. Bits that are set in both $strength and 8 are set in your example.) It's a lot more complicated than just saying that and it requires an understanding of how binary works.

EDIT: Check out this article for more information on Bitwise operators.


& is a bitwise operator - it's checking to see if the bits that total 8 are set. In this case, 1000


& is a bitwise operator. It combines two values bitwise.

What is a bitwise operator?

Every integer is internally represented as a number of bits.

1 is 0001
2 is 0010
4 is 0100
8 is 1000

And so on. every bit's value is twice as big as the one preceding it.

You can get other numbers by combining bits

3 is 0011 (2+1)
5 is 0101 (4+1)

A bitwise operation works on every bit in both variables. & sets every bit in the result to 1 if it is 1 in both values it operates on.

9&5 == 1

because

9 == 1001
5 == 0101
----------
1 == 0001

| will COMBINE all 1s:

3|5 == 7

3 == 0011
5 == 0101
---------
7 == 0111

How can yo use it?

Example:

define('LOG_WARNING',1);
define('LOG_IO',2);
define('LOG_ALIENATTACKS,4);

$myLogLevel = LOG_WARNING | LOG_ALIENATACKS;

Now $myLogLevel is a combination of LOG_WARNING and LOG_ALIENATTACK. You can test it with the & operator:

if($myLogLevel&LOG_WARNING).... //true
if($myLogLevel&LOG_IO).... //false
if($myLogLevel&LOG_ALIENATTACKS)..../ /true run or your live!!!

If you want to know more about the topic search for bitflags and binary operations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜