Recently I had an idea to try making some kind of generative music program. I got thinking about how to model harmony and musical scales etc. It seemed like the simplest way to think of an (abstract, i.e. key-less) scale was as a 12-bit binary number.
Well, ‘the thing’ will eventually have some kind of web-facing API so I’m building it in PHP. Some operations are conveniently done using just a binary number and bitwise operators, others (eg random access to individual bits) are less convenient and would benefit from a helper class of some kind.
I vaguely remembered reading about something called a BitArray, once upon a time, and it sounded handy. PHP doesn’t have one though. There were a couple of existing solutions, one of which is a bit broken and the other a bit too extended and specialised.
So I’ve borrowed ideas from both of them and made my own one, which is now up on Google Code: phpbitarray
Hopefully anyone interested in it can get by without docs… it is just one class which is pretty well commented.
One nice thing I learned was to implement some PHP5 built-in interfaces so that many of the usual things you can do with arrays (eg: for, foreach, count() and  access to elements) all work as you’d expect. It also has a full complement of bitwise and set operations as methods.
Internally it stores the value as a string of ‘0101’s which I guess is not the most efficient, though it makes random access to the bits easier. If it seems worth it I’m sure some methods could be recoded so that everything was done in binary style using an integer.