Swapping two numbers

There are two methods for swapping:
  • By using third variable.
  • Without using third variable.
Swapping Using Third Variable
				
					<?php $a = 50; $b = 83; 
echo "Before swapping:<br><br>";
echo "a =".$a." b=".$b."<br> ";
$third = $a;
$a = $b;
$b = $third; 
echo "After swapping:<br><br>";
echo "a =".$a." b=".$b; 
?>
				
			

Swapping Without using Third Variable
Swap two numbers without using a third variable is done in two ways:

  • Using arithmetic operation + and
  • Using arithmetic operation * and
  • Using arithmetic operation + and –
				
					<?php 
$a=567; 
$b=789; 
echo " Before Swapping:<br>"; 
echo "Value of a: $a</br>"; 
echo "Value of b: $b</br>"; 
$a=$a+$b; 
$b=$a-$b;
$a=$a-$b;
echo " After Swapping:<br>"; 
echo "Value of a: $a</br>";
echo "Value of b: $b</br>";
?>
				
			
Using arithmetic operation * and /
				
					<?php 
$a=890; 
$b=908; 
echo " Before Swapping:<br>"; 
echo "Value of a: $a</br>";
echo "Value of b: $b</br>";
$a=$a*$b; 
$b=$a/$b; 
$a=$a/$b; 
echo " After Swapping:<br>"; 
echo "Value of a: $a</br>";
echo "Value of b: $b</br>"; ?>
				
			

Leave a Reply