phpbit-manipulationbitwise-operatorsbitwise-orinput-parameters

How To Test PHP Bitwise Function Input Parameters


Sometimes in programming they allow one to chain parameters in a single function input variable like the second input variable below:

define('FLAGA',40);
define('FLAGB',10);
define('FLAGC',3);
function foo($sFile, $vFlags) {
  // do something
}
foo('test.txt',FLAGA | FLAGB | FLAGC);

PHP calls this single pipe character (|) the Bitwise OR operator. How do I now add something inside foo() to test $vFlags to see which flags were set?


Solution

  • I think you'll find that flags like this are normally defined as powers of 2, e.g.:

    define('FLAGA',1);
    define('FLAGB',2);
    define('FLAGC',4); /* then 8, 16, 32, etc... */
    

    As you rightly stated, these can be combined by using a bitwise OR operator:

    foo('test.txt',FLAGA | FLAGB | FLAGC);
    

    To test these flags inside your function, you need to use a bitwise AND operator as follows:

    function foo($sFile, $vFlags) {
      if ($vFlags & FLAGA) {
        // FLAGA was set
      }
      if ($vFlags & FLAGB) {
        // FLAGB was set
      }
      //// etc...
    }