Two numbers can be swapped or exchanged. It means first number will become second and second number will become first.
For example
Originally
a = 20, b = 25
After swapped it will become
a = 25, b = 20
Swapping can be done by 2 ways.
- Using third (temporary) variable
- without using third (temporary) variable
Using Third Variable
<?php
$a = 20;
$b = 25;
echo "Without exchange a = $a and b = $b";
$temp = $a;
$a = $b;
$b = $temp;
echo "<br/> After exchange <b> a = $a </b> and <b> b = $b </b>";
?>
swap 2 variables without using third variable.
<?php
$a = 20;
$b = 25;
echo "Without exchange a = $a and b = $b";
$a = $a + $b; // 20 + 25 = 45
$b = $a - $b; // 45 - 25 = 20
$a = $a - $b; // 45 - 20 = 25
echo "<br/> <br/> After exchange <b> a = $a </b> and <b> b = $b </b>";
?>
Note: br or b used for break line and bold.