2 variable swap using XOR

Hello all I’m new to the forums here… I have a project I’m working on and it requires me to swap the values of two variables x & y.

here is what I have so far:
[php]<?php

$x = 3;
$y = 0.14;
function switch_values(){
global $x, $y;
$x^=$y;
$y^=$x;
$x^=$y;

}
$outcome = switch_values($x, $y);
if (round($x, 2) == 0.14 &&
round($y, 2) == 3 ) {
print “It worked!”;
} else {
print “Try again!”;

}

?>[/php]
Any help appreciated thank you!!

You do not have to declare variables as global, just pass them as function arguments. The function is really simple:
[php]<?php

function switch_values(&$x,&$y){
$z=$x;
$x=$y;
$y=$z;
}

// Testing

$x=1;
$y=2;

echo ‘Old values:
’;
echo ‘x = ‘.$x.’
’;
echo ‘y = ‘.$y.’
’;

switch_values($x,$y);

echo ‘New values:
’;
echo ‘x = ‘.$x.’
’;
echo ‘y = ‘.$y.’
’;

?>
[/php]

I was looking to do this with a XOR function though, rather than declare a whole new variable. Any thoughts?

Sponsor our Newsletter | Privacy Policy | Terms of Service