➤ Two numbers can be swapped or interchanged. It means first number
will become second and second number will become first.
For instance:
• Swapping Using Third Variable
$x = 5;
$y = 10;
// Swapping Logic
$temp = $x;
$x = $y;
$y = $temp;
echo "After swapping: ";
echo "\n x = $x \n y = $y";
// outputs : x = 10 y = 5
• Swap two numbers without using a third variable
- Using arithmetic operation + and ?
$x = 5;
$y = 10;
$x = $x + $y; // 15
$y = $x - $y; // 5
$x = $x - $y; // 10
echo "After swapping: ";
echo "\n x = $x \n y = $y";
// outputs : x = 10 y = 5
- Using arithmetic operation * and /
$x = 5;
$y = 10;
$x = $x*$y; // 50
$y = $x/$y; // 5
$x = $x/$y; // 10
echo "After swapping: ";
echo "\n x = $x \n y = $y";
// outputs : x = 10 y = 5