& is a bit wise AND. What this means is that the AND is done in binary. So, let's play:
0 = 00000000
1 = 00000001
2 = 00000010
3 = 00000011
4 = 00000100
5 = 00000101
6 = 00000110
7 = 00000111
8 = 00001000
and so on.
So, let's bitwise and a few of these. An and function produces 1 for inputs of 1 and 1, and 0 for all else, so:
0 & anything = 0 (00000000 & xxxxxxxx)
1 & 2 = 0 (00000001 & 00000010)
2 & 3 = 2 (00000010 & 00000011)
5 & 13 = 5 (00000101 & 00001111)
127 & 13 = 13 (01111111 & 00001111)
So, that part of your code that has:
if ($x & 4) is really saying that anytime that the bit inside $x representing 4 is turned on, return true. If we look at the output, we see this:
0 to 3 & 4 = 0
4 to 7 & 4 = 4
8 to 11 & 4 = 0
12 to 15 & 4 = 4
and so on, so it switches on (or off) every time $x cycles four times.