Swap Two Numbers using Bitwise XOR Operator

Another way to swap two numbers without using a temporary variable is by using the bitwise XOR (^) operator.

PHP




<?php
    
$a = 10;
$b = 20;
  
echo "Before swapping: a = $a, b = $b\n";
  
// Swapping Operation
$a = $a ^ $b;
$b = $a ^ $b;
$a = $a ^ $b;
  
echo "After swapping: a = $a, b = $b\n";
  
?>


Output

Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10


Explanation:

  • The XOR operation is used to toggle the bits in the numbers.
  • After the first operation, a holds the combined bits of a and b.
  • After the second operation, b becomes the original value of a.
  • After the third operation, a becomes the original value of b.
  • This method effectively swaps the values of a and b without using a temporary variable.


Swap Two Numbers Without using a Temporary Variable in PHP

Given two numbers, the task is to swap both numbers without using temporary variables in PHP. Swapping two numbers is a common programming task. Typically, a temporary variable is used to hold the value of one of the numbers during the swap. However, it is also possible to swap two numbers without using a temporary variable. In this article, we will explore a PHP program that accomplishes this using arithmetic operations.

Table of Content

  • Swap Two Numbers using Arithmetic Operations
  • Swap Two Numbers using Bitwise XOR Operator

Similar Reads

Swap Two Numbers using Arithmetic Operations

One way to swap two numbers without using a temporary variable is by using arithmetic operations such as addition and subtraction....

Swap Two Numbers using Bitwise XOR Operator

...