The ^
is the exclusive or operator, which means that we're in reality working with binary values. So lets break down what happens.
The XOR operator on binary values will return 1
where just one of the bits were 1, otherwise it returns 0 (0^0 = 0
, 0^1 = 1
, 1^0 = 1
, 1^1 = 0
).
As you said yourself, when you use XOR
on characters, you're using their ASCII values. These ASCII values are integers, so we need to convert those to binary to see what's actually going on. Let's use your first example, A
and }
.
$first = 'A';
$second = '}';
$ascii_first = ord($first); // 65
$ascii_second = ord($second); // 125
We then convert these to binary using the decbin()
function.
$binary_first = decbin($ascii_first); // 1000001
$binary_second = decbin($ascii_second); // 1111101
Now we use the XOR
operator on those binary values.
first 1000001
^
second 1111101
-------------------
result 0111100
We see the binary value we get is 0111100
. Using the bindec()
function we reverse it back to an integer value
$final_ascii = bindec("0111100"); // 60
We see we get the integer value 60 back. Using chr(60)
you will get the character which has the decimal value of 60 in the ASCII table - the result is <
.
Here's a live demo that shows the steps: https://3v4l.org/Xd8SP - you can play around with it, substituting characters to see the end result of different combinations of characters.