Here is an easy way to use bitwise operation for 'flag' functionality.
By this I mean managing a set of options which can either be ON or OFF, where zero or more of these options may be set and each option may only be set once. (If you are familiar with MySQL, think 'set' datatype).
Note: to older programmers, this will be obvious.
Here is the code:
<?php
function set_bitflag(/*variable-length args*/)
{
$val = 0;
foreach(func_get_args() as $flag) $val = $val | $flag;
return $val;
}
function is_bitflag_set($val, $flag)
{
return (($val & $flag) === $flag);
}
// Define your flags
define('MYFLAGONE', 1); // 0001
define('MYFLAGTWO', 2); // 0010
define('MYFLAGTHREE', 4); // 0100
define('MYFLAGFOUR', 8); // 1000
?>
I should point out: your flags are stored in a single integer. You can store loads of flags in a single integer.
To use my functions, say you wanted to set MYFLAGONE and MYFLAGTHREE, you would use:
<?php
$myflags = set_bitflags(MYFLAGONE, MYFLAGTHREE);
?>
Note: you can pass set_bitflags() as many flags to set as you want.
When you want to test later if a certain flag is set, use e.g.:
<?php
if(is_bitflag_set($myflags, MYFLAGTWO))
{
echo "MYFLAGTWO is set!";
}
?>
The only tricky part is defining your flags. Here is the process:
1. Write a list of your flags
2. Count them
3. Define the last flag in your list as 1 times 2 to the power of <count> minus one. ( I.E. 1*2^(<count>-1) )
3. Working backwards through your list, from the last to the first, define each one as half of the previous one. You should reach 1 when you get to the first
If you want to understand binary numbers, bits and bitwise operation better, the wikipedia page explains it well - http://en.wikipedia.org/wiki/Bitwise_operation.