Bitwise operators are a very handy tool that can be used in PHP. The problem is they just aren’t used very often. I really like bitwise operators, but like other PHP developers, I just don’t use them very often. I think the cause of this is that developers just don’t realize when they COULD be using bitwise operators.
A very good example of where you should be using bitwise operators is in Access Control Lists (ACLs). An ACL is basically a list of who has access to what. Well, a simple way to introduce you to access control is via Unix permissions. Most of you are probably familiar with the chmod command. Most of you also probably don’t have the codes memorized. Here is a great little PHP script that will:
A: Help you understand bitwise operators and how you might use them, and
B: Help you understand and memorize the chmod codes.
define("EXECUTE", 1);
define("WRITE", 2);
define("READ", 4);
for($i = 0; $i <= 7; $i++) {
$x = ($i & EXECUTE) ? "x" : "-";
$w = ($i & WRITE) ? "w" : "-";
$r = ($i & READ) ? "r" : "-";
echo "{$i} = {$r}{$w}{$x}<br />";
}
This will output:
1 = ––x
2 = –w–
3 = –wx
4 = r––
5 = r–x
6 = rw–
7 = rwx
A little note, about chmod, just in case you were wondering now: a chmod code is three digits. The first digit is the access code for the file’s owner, the second digit is the access code for the group of the file’s owner, and the third digit is the access code for everyone else. So, let’s take a code: 754. What does this mean? Well, let’s use that list we just created to look it up. The first digit, 7, as stated, maps to the file’s owner, so according to our list, the owner has full permissions, rwx. Next, the second digit is a 5, and that maps to the file owner’s group; the group has r-x access: read and execute, but no write permissions. The final digit, everyone else, is a 4: read-only access.
Now, how can you apply this to your code? Well, as long as you keep the integer assignments as powers of 2, you can have an infinite number of access codes:
define("MAGIC", 8);
$wizard = READ | WRITE | EXECUTE | MAGIC;
if($wizard & MAGIC) {
echo "Wizards can do magic <br />";
}

