PHP if question with instruction (& operator)

I am using a function that I found on the Internet. What does this mean in this conditional?

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

$ It is assumed that the strength is 0-8. The function intends to use all the consonants of $ consonants, where $ strength <8. (may explain why the function does not work).

+4
source share
3 answers

One & is a bitwise operator, and double && is a boolean. (i.e., the bits that are set in both $strength and 8 are set in your example.) This is much more complicated than just saying this, and this requires an understanding of how the binary works.

EDIT: Check out this article for more information about bitwise operators.

+4
source

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

+3
source

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

What is a bitwise operator?

Each integer is internally represented as several bits.

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

And so on. each bit value is two times larger than the previous one.

You can get other numbers by combining bits

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

Bitwise operation works with each bit in both variables. & sets each bit as a result of 1 if it is 1 in both the values ​​it works on.

9 & 5 == 1

because

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

| there will be a COMBINE of all 1s:

3 | 5 == 7

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

How can you 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 check 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 topic search for bit flags and binary operations.

+3
source

Source: https://habr.com/ru/post/1334715/


All Articles