Saw stuff like `error_reporting(E_ERROR | E_WARNING | E_PARSE);` or heard about bitmasks and got confused how it actually works? To my shame I never looked it up in like 12 years of programming until now.

What it actually is, is a quite efficient way to define for example grants for a user or which features are enabled for an application. It’s also quite old school but often seen and still in use.

At this point I’d suggest you to also open the PHP documentation where they explain all existing bitwise operators. I created some examples here to make it easier to understand and to visualise what is happening.

``````                      // Decimal in binary
// 2^4 2^3 2^2 2^1

\$a = 1;               // 0   0   0   1
\$b = 2;               // 0   0   1   0
\$c = 4;               // 0   1   0   0
\$d = 8;               // 1   0   0   0

\$ab = \$a | \$b;        // 0   0   1   1
// = | sets the bits which are either set in \$a or \$b

\$abc = \$a | \$b | \$c;  // 0   1   1   1
// = | sets the bits which are either set in \$a, \$b or \$c

\$ab & \$a;             // 0   0   0   1
// = \$ab has bit \$a set, the result equals \$a

\$ab & \$c;             // 0   0   0   0
// = \$ab has \$c not set, the result equals 0

\$ab & \$b;             // 0   0   1   0
// = \$ab has \$b set, the result equals \$b

\$ab & (\$a | \$b);      // 0   0   1   1
// = \$ab has bit \$a and bit \$b set

\$ab & (\$a | \$b | \$c); // 0   0   1   1
// = \$ab has \$a and \$b set but \$c``````

So what we’ve learned:

• We have a 4 bits and we assign a meaning to each of them
• We can individually switch single bits to express a state
• Bitwise operations are supposed to be very fast and efficient
• Use only numbers with a power of 2, otherwise we would mess up the bitmask because the binary system represent a number which is not of the power of 2 by two or more bits
• Using a bitmask for a simple ACL system and putting each grant into a const might even make it readable and easy to work with

Would I use it? Maybe or maybe not it really depends on what I exactly need. It’s fast and solid when done right but will become messy when it’s getting much more complex. But in case you run into legacy code as I did this might help you to understand it.