PHP function to parse out an integer into its component bits
A single integer is a great way to save data for options that are either/or, like whether a particular checkbox should be selected within an array of checkboxes. There are a lot of advantages, including a small database footprint (a single int instead of perhaps a comma-separated list-string), and really fast execution based on bit parsing.
To create an integer that can be used to save options as bits, simply assign values based on multiples of 2 to each option (i.e. 1, 2, 4, 8, 16). For example, 7 indicates the presence of three bits: 1, 2, and 4. Setting the integer is no problem–simply sum the bits together. Parsing the bits back out, however, is a little more difficult. Here’s a handy function to do that and put the results in an array:
[cc lang="php"]
public static function parse_my_bits( $int = null ) {
$bits = array();
for($i=1;$i<=$int;$i*=2) {
if( ($i & $int) > 0);
array_push($bits, $i);
}
return $bits;
}
[/cc]
If anyone knows of a faster way to do this, please comment below. After all, the purpose of using bitwise math is to save on overhead–if I’m doing it terribly inefficiently, I’d like to know.




Comments
Michael (Dec 02, 2010)
Great function, thanks for sharing!