Saturday, February 28, 2015

swaping two numeric value

Here listed five method of swaping two numeric(integer) value.

method 1: Assign the value of the second variable to the first variable. Third temporary variable $temp is used to hold the value of the first variable so it’s value can't be lost.


$x = 1;
$y = 2;
$temp = '';
$temp = $x;
$x = $y;
$y = $temp;
echo 'Value of X: '.$x;
echo 'Value of Y: '.$y;


method 2: Using php function array and list.


$x = 3;
$y = 4;
list($x, $y) = array($y, $x);
echo 'Value of X: '.$x;
echo 'Value of Y: '.$y;


method 3: Using addition and subtraction


$x = 5;
$y = 6;

$x = $x + $y;
$y = $x - $y;
$x = $x - $y;

echo 'Value of X: '.$x;
echo 'Value of Y: '.$y;


method 4: Using Division  and multiplication


$x = 7;
$y = 8;

$x = $x * $y;
$y = $x / $y;
$x = $x / $y;

echo 'Value of X: '.$x;
echo 'Value of Y: '.$y;



method 5:  using XOR method


$x = 9;
$y = 10;

$x = $x ^ $y;
$y = $x ^ $y;
$x = $x ^ $y;

echo 'Value of X: '.$x;
echo 'Value of Y: '.$y;


Disadvantage of this method is difficult to understand the process.

No comments:

Post a Comment