What happend $a & $b and $a | $b in php ?
$a = 11;
$b = 7;
echo $a & $b;
In the above php code it will give result 3 How it will calculate 3 ?
$a = 11;
$b = 7;
echo $a | $b;
In the above php code it will give result 15 How it will calculate 15?
Explain me both condition in php?
What's happening here is something called Bitwise Operators . It's more often used in much lower level languages, and it's one of the very simplest things a computer can do. Most computation is built on top of it. So what is it? Well, &
is the Bitwise AND
operator, and |
is the Bitwise OR
operator. You can test them with this online tool . But let's breakdown how it works.
Take two binary strings and any 1
's that aren't in both binaries, the the same place, become a 0
.
7
is 111
11
is 1011
So if you perform an AND
on them, you get something like this
0111 &
1011 =
0011
0011
in Decimal is 3
. You get 0011
because only the last two places are BOTH 1
.
OR
is basically the opsite. If a position in either binary is 1
, then the output is 1
. So when you perform it on 7
and 11
, you'll get
1011 |
0111 =
1111
And 1111
is 15
in decimal
In binary, 11
is 00001011
and 7
is 00000111
(showing only relevant 8 bits for simplicity).
So 11 & 7
(bitwise AND)
00001011
00000111 & matching only where both matching bits are `1`
--------
00000011
which is the binary for 3
So 11 | 7
11 | 7
(bitwise OR)
00001011
00000111 | matching where either (or both) bits is `1`
--------
00001111
which is the binary for 15
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.