Taylor Taylor - 1 month ago 5
PHP Question

Is there a PHP function for swapping the values of two variables?

Say for instance I have ...

$var1 = "ABC"
$var2 = 123

and under certain conditions I want to swap the two around like so...

$var1 = 123
$var2 = "ABC"

Is there a PHP function for doing this rather than having to create a 3rd variable to hold one of the values then redefining each, like so...

$var3 = $var1
$var1 = $var2
$var2 = $var3

For such a simple task its probably quicker using a 3rd variable anyway and I could always create my own function if I really wanted to. Just wondered if something like that exists?


There isn't a built-in function.

As many mentioned, there are 3 methods to do this:

function swap1(&$x,&$y) {
    $x ^= $y ^= $x ^= $y;
function swap2(&$x,&$y) {
    list($x,$y) = array($y,$x);
function swap3(&$x,&$y) {

I tested the 3 methods under a for-loop of 1000 iterations, to find the fastest of them:

  • swap1 = scored approximate average of 0.19 seconds.
  • swap2 = scored approximate average of 0.42 seconds.
  • swap3 = scored approximate average of 0.16 seconds.

And for readability/writability, IMO I find swap3 is better than the other 2 functions.