I can’t understand how the following code works.
$start = 1;
while($start<10){
if ($start&1) {
echo "ODD ".$start." <br/> ";
}
else {
echo "EVEN ".$start." <br/> ";
}
$start++;
}
The $start&1 will return ODD and EVEN seperately.
Output
ODD 1
EVEN 2
ODD 3
EVEN 4
ODD 5
EVEN 6
ODD 7
EVEN 8
ODD 9
If we give $start&2 instead of $start&1, it returns with another order.
How &1 &2 etc… works here?
It is a bitwise and operator.
Depending on the endianness, it will be either the leftmost or rightmost bit that matters in this check. The above is &ing with 1. In your second example, &ing with 2, that would be
And for further comparison, here is 1-3 &ing with 3
To see what is going on, follow the columns of the two numbers down. If they are both a 1 then the result has the bit set in that position to a 1. If either are a 0 then the result is a 0 in that position. So for 2 & 3..