
We have two variables (parameters) “x” & “y”, here we do swap of two variables without using a third variable (parameters).
1) Swap numbers using Arithmetic Operators –
In below example we use addition and subtraction operation to do swap of 2 numbers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
<?php function swap_me() { $x = 25; $y = 14; echo "Before Swapping: x = ".$x.", y = ".$y; // Code to swap "$x" and "$y" $x = $x + $y; // $x now becomes 39 $y = $x - $y; // $y becomes 25 $x = $x - $y; // $x becomes 14 echo "<BR>After Swapping: x = ".$x.", y = ".$y; } // call the function swap_me(); ?> Output: Before Swapping: x = 25, y = 14 After Swapping: x = 14, y = 25 |
In below example we use multiplication and division operation to do swap of 2 numbers
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php function swap_me() { $x = 25; $y = 14; echo "Before Swapping: x = ".$x.", y = ".$y; // Code to swap "$x" and "$y" $x = $x * $y; // x now becomes 350 $y = $x / $y; // y becomes 25 $x = $x / $y; // x becomes 14 echo "<BR>After Swapping: x = ".$x.", y = ".$y; } // call the function swap_me(); ?> Output: Before Swapping: x = 25, y = 14 After Swapping: x = 14, y = 25 |
2) Swap numbers using Bitwise XOR Operators –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php function swap_me() { $x = 25; $y = 14; echo "Before Swapping: x = ".$x.", y = ".$y; // Code to swap 'x' (11001) and 'y' (1110) $x = $x ^ $y; // x now becomes 15 (100111) $y = $x ^ $y; // y becomes 10 (11001) $x = $x ^ $y; // x becomes 5 (1110) echo "<BR>After Swapping: x = ".$x.", y = ".$y; } // call the function swap_me(); ?> Output: Before Swapping: x = 25, y = 14 After Swapping: x = 14, y = 25 |
Note:
In multiplication, we can not able to use 0 (zero), because of it make multiplication result as zero.
Your comments are appreciated!
Till than Happy Coding 🙂
Nice logical twist. keep on updates of such amazing code snippet 🙂