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 & 1it will then tell you if the ‘1’ flag is set, such as in binary:
001010111010The 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 & 1will 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 & 1will be false.