Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the significance of '^' in PHP?
The '^' is a bitwise XOR (exclusive OR) operator in PHP that performs bitwise operations on operands. For each bit position, it returns 1 if the bits are different and 0 if they are the same. When used with strings, it operates on the ASCII values of characters.
How XOR Works
The XOR operator compares each bit of the first operand with the corresponding bit of the second operand −
- If bits are different: returns 1
- If bits are the same: returns 0
Example with Numbers
Here's how XOR works with integer values −
<?php
$a = 5; // Binary: 101
$b = 3; // Binary: 011
$result = $a ^ $b;
echo "5 ^ 3 = " . $result;
echo "<br>";
// Step by step:
// 101 (5)
// 011 (3)
// --- XOR
// 110 (6)
?>
5 ^ 3 = 6
Variable Swapping with XOR
A clever use of XOR is swapping variables without a temporary variable −
<?php
$x = "a";
$y = "b";
echo "Before swap: x = $x, y = $y<br>";
$x ^= $y;
$y ^= $x;
$x ^= $y;
echo "After swap: x = $x, y = $y";
?>
Before swap: x = a, y = b After swap: x = b, y = a
XOR with Different Data Types
XOR can be applied to integers and strings −
<?php
// With integers
echo "Integer XOR: " . (12 ^ 7) . "<br>";
// With characters (ASCII values)
echo "Character XOR: " . ('A' ^ 'B') . "<br>";
// XOR assignment operator
$num = 10;
$num ^= 5;
echo "XOR assignment: " . $num;
?>
Integer XOR: 11 Character XOR: XOR assignment: 15
Conclusion
The '^' operator in PHP is a powerful bitwise XOR operator that compares bits and returns 1 for different bits, 0 for same bits. It's commonly used in variable swapping, encryption algorithms, and bitwise manipulations.
