How to implement a bitmask in php?

It’s quite simple actually. First a bit of code to demonstrate how it can be implemented. If you don’t understand anything about what this code is doing or how it works, feel free to ask additional questions in the comments:

const FLAG_1 = 0b0001; // 1
const FLAG_2 = 0b0010; // 2
const FLAG_3 = 0b0100; // 4
const FLAG_4 = 0b1000; // 8
// Can you see the pattern? ;-)

function show_flags ($flags) {
  if ($flags & FLAG_1) {
    echo "You passed flag 1!<br>\n";
  }
  if ($flags & FLAG_2) {
    echo "You passed flag 2!<br>\n";
  }
  if ($flags & FLAG_3) {
    echo "You passed flag 3!<br>\n";
  }
  if ($flags & FLAG_4) {
    echo "You passed flag 4!<br>\n";
  }
}

show_flags(FLAG_1 | FLAG_3);

Demo


Because the flags are integers, on a 32-bit platform you define up to 32 flags. On a 64-bit platform, it’s 64. It is also possible to define the flags as strings, in which case the number of available flags is more or less infinite (within the bounds of system resources, of course). Here’s how it works in binary (cut down to 8-bit integers for simplicity).

FLAG_1
Dec:    1
Binary: 00000001

FLAG_2
Dec:    2
Binary: 00000010

FLAG_3
Dec:    4
Binary: 00000100

// And so on...

When you combine the flags to pass them to the function, you OR them together. Let’s take a look at what happens when we pass FLAG_1 | FLAG_3

  00000001
| 00000100
= 00000101

And when you want to see which flags were set, you AND the bitmask with the flag. So, lets take the result above and see if FLAG_3 was set:

  00000101
& 00000100
= 00000100

…we get the value of the flag back, a non-zero integer – but if we see if FLAG_2 was set:

  00000101
& 00000010
= 00000000

…we get zero. This means that you can simply evaluate the result of the AND operation as a boolean when checking if the value was passed.

Leave a Comment