Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ^ operator in PHP is the bitwise XOR (exclusive OR) operator. It evaluates two operands at the binary level, comparing their corresponding bits. It returns 1 if the bits at a given position are strictly different, and 0 if they are identical.

Truth Table

For any two bits (AA and BB), the XOR operation yields the following:
  • 0 ^ 0 = 0
  • 0 ^ 1 = 1
  • 1 ^ 0 = 1
  • 1 ^ 1 = 0

Integer Evaluation

When both operands are integers, PHP converts them to their binary representations, aligns them, and applies the XOR logic to each bit column.
$a = 12; // Binary: 1100
$b = 10; // Binary: 1010

$result = $a ^ $b; 
// Binary evaluation:
//   1100
// ^ 1010
// ---
//   0110  -> Converts back to decimal: 6

echo $result; // Outputs: 6

Floating-Point Evaluation

If an operand is a float, PHP implicitly truncates the fractional part, converting it to an int before performing the bitwise XOR operation. As of PHP 8.1, implicitly converting a float with a fractional part to an integer is deprecated and will emit a deprecation notice due to the loss of precision.
$a = 12.9; // Truncated to 12 (Binary: 1100)
$b = 10.1; // Truncated to 10 (Binary: 1010)

$result = $a ^ $b; 
// Evaluates as 12 ^ 10

echo $result; 
// Outputs in PHP 8.1+:
// Deprecated: Implicit conversion from float 12.9 to int loses precision...
// Deprecated: Implicit conversion from float 10.1 to int loses precision...
// 6

String Evaluation

If both operands are strings, PHP performs the bitwise XOR operation on the ASCII (or byte) values of the corresponding characters, byte-by-byte.
$str1 = "A"; // ASCII 65  (Binary: 01000001)
$str2 = " "; // ASCII 32  (Binary: 00100000)

$result = $str1 ^ $str2; 
// Binary evaluation:
//   01000001
// ^ 00100000
// -------
//   01100001 -> ASCII 97 ("a")

echo $result; // Outputs: "a"
Note on String Lengths: If the strings are of unequal length, the shorter string is implicitly padded with null bytes (\0) to match the length of the longer string before the XOR operation is executed.

Mixed Type Coercion

If the operands are of mixed types (e.g., one integer and one string), PHP will implicitly cast the string to an integer before performing the bitwise operation. As of PHP 8.0, if the string cannot be parsed as a valid numeric value, PHP throws a TypeError.
$int = 5;      // Binary: 0101
$str = "3";    // Cast to integer 3 (Binary: 0011)

$result = $int ^ $str; 
// Binary: 0110 -> Decimal: 6

echo $result; // Outputs: 6

// PHP 8.0+ behavior for non-numeric strings
$errorResult = 5 ^ "text"; 
// Fatal error: Uncaught TypeError: Unsupported operand types: int ^ string
Master PHP with Deep Grasping Methodology!Learn More