Swap two variables value without using third variable in php
| Bit in Expression1 | Bit in Expression2 | Result |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
Example with two variable by XOR: 
$a = 5; // 5 => 00000101
$b = 6; // 6 => 00000110
$a = $a ^ $b; // 3 => 00000011 Now XOR of 5 and 6 is 3
$b = $a ^ $b; // 5 => 00000101 Now XOR of 6 and 3 is 5
$a = $a ^ $b; // 6 => 00000110 Now XOR of 3 and 5 is 6

$a = 5; // 5 => 00000101
$b = 6; // 6 => 00000110
$a = $a ^ $b; // 3 => 00000011 Now XOR of 5 and 6 is 3
$b = $a ^ $b; // 5 => 00000101 Now XOR of 6 and 3 is 5
$a = $a ^ $b; // 6 => 00000110 Now XOR of 3 and 5 is 6
echo $a.” “.$b; // Output will be $a=6; $b=5

Leave a Reply
Want to join the discussion?Feel free to contribute!