Looking at some code written by another developer, I came across this:
for($i=1; $i<=30; $i++)
{
if($i&1)
$color = '#fff';
else
$color = '#bbb';
}
This $color variable is used for row background colour later in the code. The alternating colours work fine.
If I was writing this, I would have used the modulus operator (%) rather than the bitwise (&) operator.
Why does the bitwise operator work in this case? Is there any advantage of using this method rather than the modulus operator?
The &
operator does a bitwise comparison on the number. So if you do
$i & 1
it will then tell you if the '1' flag is set, such as in binary:
001010111010
The last number is the '1' flag (remember, binary goes 1, 2, 4, 8 etc. in reverse order), which in this case is set to 0.
Since 1 is the only odd flag in binary, it will tell you if the number is odd or even.
if $i is 3 for example, then in binary it will be 011 - the last number is a 1 (the 1 flag) and thus $i & 1
will be true.
if $i is 4 for example, then in binary it will be 100 - the last number is a 0 (the 1 flag) and thus $i & 1
will be false.
It works because the first bit is always 1 if the number is odd and 0 if the number is even.
1
10
11
100
101
110
111
etc.
In theory bitwise operation is faster than the modulus operation, but it's possible that the interpreter would have optimized the modulus operation down to bitwise operation anyway.
Why the other developer used it, we can only guess: out of habit, copy-pasted from somewhere, doesn't know about the modulus operator, showing off, wanting to optimize...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With