I’ve created a short and sweet PHP function swap() to exchange/swap the values of two PHP variables. Here it is in action:
<?php $cat = "cat"; $dog = "dog"; swap($cat,$dog); echo "$cat goes meow and $dog goes woof"; //dog goes meow and cat goes woof function swap(&$var1, &$var2) { $tmp = $var1; $var1 = $var2; $var2 = $tmp; } ?>
If you’re running this function a lot (e.g. millions of iterations) it’s actually faster to just perform the swap without the function. For example:
for($i = 0; $i < 10000000; $i++) { $tmp = $var1; $var1 = $var2; $var2 = $tmp; }
Thanks @dnaslave for providing efficiency feedback! :]