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
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 andb
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
andb
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 ofa
andb
. - After the second operation,
b
becomes the original value ofa
. - After the third operation,
a
becomes the original value ofb
. - This method effectively swaps the values of
a
andb
without using a temporary variable.
Contact Us