Open In App

Swap Two Numbers Without using a Temporary Variable in PHP

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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.

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:

  • Initially, a is 10 and b is 20.
  • After the first operation, a becomes 30 (10 + 20).
  • After the second operation, b becomes 10 (30 – 20).
  • After the third operation, a becomes 20 (30 – 10).
  • As a result, the values of a and b are swapped without using a temporary variable.

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.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads