Say for instance I have ...
$var1 = \"ABC\"
$var2 = 123
and under certain conditions I want to sw
There's no function I know of, but there is a one-liner courtesy of Pete Graham:
list($a,$b) = array($b,$a);
not sure whether I like this from a maintenance perspective, though, as it's not really intuitive to understand.
Also, as @Paul Dixon points out, it is not very efficient, and is costlier than using a temporary variable. Possibly of note in a very big loop.
However, a situation where this is necessary smells a bit wrong to me, anyway. If you want to discuss it: What do you need this for?
Yes I know there are lots of solutions available, but here is another one.
You can use parse_str()
function too. Reference W3Schools PHP parse_str() function.
<?php
$a = 10;
$b = 'String';
echo '$a is '.$a;
echo '....';
echo '$b is '.$b;
parse_str("a=$b&b=$a");
echo '....After Using Parse Str....';
echo '$a is '.$a;
echo '....';
echo '$b is '.$b;
?>
DEMO
Thanks for the help. I've made this into a PHP function swap()
function swap(&$var1, &$var2) {
$tmp = $var1;
$var1 = $var2;
$var2 = $tmp;
}
Code example can be found at:
http://liljosh.com/swap-php-variables/
Yes, try this:
// Test variables
$a = "content a";
$b = "content b";
// Swap $a and $b
list($a, $b) = array($b, $a);
This reminds me of python, where syntax like this is perfectly valid:
a, b = b, a
It's a shame you can't just do the above in PHP...
another simple method
$a=122;
$b=343;
extract(array('a'=>$b,'b'=>$a));
echo '$a='.$a.PHP_EOL;
echo '$b='.$b;
3 options:
$x ^= $y ^= $x ^= $y; //bitwise operators
or:
list($x,$y) = array($y,$x);
or:
$tmp=$x; $x=$y; $y=$tmp;
I think that the first option is the fastest and needs lesser memory, but it doesn’t works well with all types of variables. (example: works well only for strings with the same length)
Anyway, this method is much better than the arithmetic method, from any angle.
(Arithmetic: {$a=($a+$b)-$a; $b=($a+$b)-$b;} problem of MaxInt, and more...)
Functions for example:
function swap(&$x,&$y) { $x ^= $y ^= $x ^= $y; }
function swap(&$x,&$y) { list($x,$y) = array($y,$x); }
function swap(&$x,&$y) { $tmp=$x; $x=$y; $y=$tmp; }
//usage:
swap($x,$y);