Say for instance I have ...
$var1 = \"ABC\"
$var2 = 123
and under certain conditions I want to sw
$a=5; $b=10; $a=($a+$b)-$a; $b=($a+$b)-$b;
list($var1,$var2) = array($var2,$var1);
This one is faster and needs lesser memory.
function swap(&$a, &$b) {
$a = $a ^ $b;
$b = $a ^ $b;
$a = $a ^ $b;
}
$a = "One - 1";
$b = "Two - 2";
echo $a . $b; // One - 1Two - 2
swap($a, $b);
echo $a . $b; // Two - 2One - 1
Working example: http://codepad.viper-7.com/ytAIR4
another answer
$a = $a*$b;
$b = $a/$b;
$a = $a/$b;
Yes, there now exists something like that. It's not a function but a language construct (available since PHP 7.1). It allows this short syntax:
[$a, $b] = [$b, $a];
See "Square bracket syntax for array destructuring assignment" for more details.
Here is another way without using a temp or a third variable.
<?php
$a = "One - 1";
$b = "Two - 2";
list($b, $a) = array($a, $b);
echo $a . $b;
?>
And if you want to make it a function:
<?php
function swapValues(&$a, &$b) {
list($b, $a) = array($a, $b);
}
$a = 10;
$b = 20;
swapValues($a, $b);
echo $a;
echo '<br>';
echo $b;
?>