是否有一个 PHP 函数用于交换两个变量的值?

比如说我有..。

$var1 = "ABC"
$var2 = 123

在一定条件下,我要把两个交换,就像这样..。

$var1 = 123
$var2 = "ABC"

是否有一个 PHP 函数可以做到这一点,而不是必须创建第三个变量来保存其中一个值,然后重新定义每个值,如下所示..。

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

对于这样一个简单的任务,使用第三个变量可能会更快,如果我真的想的话,我总是可以创建自己的函数。只是想知道是否有这样的东西存在?

更新: 使用第三个变量或将其包装在函数中是最佳解决方案。简单明了。我问这个问题更多的是出于好奇,所选择的答案有点像是“下一个最好的选择”。只要用第三个变量。

77406 次浏览

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?

list($var1,$var2) = array($var2,$var1);

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...

It is also possible to use the old XOR trick ( However it works only correctly for integers, and it doesn't make code easier to read.. )

$a ^= $b ^= $a ^= $b;

If both variables are integers you can use mathematical approach:

$a = 7; $b = 10; $a = $a + $b; $b = $a - $b; $a = $a - $b;

Good blog post - http://booleandreams.wordpress.com/2008/07/30/how-to-swap-values-of-two-variables-without-using-a-third-variable/

$a=5; $b=10; $a=($a+$b)-$a; $b=($a+$b)-$b;

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 way:

$a = $b + $a - ($b = $a);

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;
?>

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/

For numbers:

$a = $a+$b;
$b = $a-$b;
$a = $a-$b;

Working:

Let $a = 10, $b = 20.

$a = $a+$b (now, $a = 30, $b = 20)

$b = $a-$b (now, $a = 30, $b = 10)

$a = $a-$b (now, $a = 20, $b = 10 SWAPPED!)

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);

another answer

$a = $a*$b;
$b = $a/$b;
$a = $a/$b;

another simple method

$a=122;
$b=343;


extract(array('a'=>$b,'b'=>$a));


echo '$a='.$a.PHP_EOL;
echo '$b='.$b;

TL;DR

There isn't a built-in function. Use swap3() as mentioned below.

Summary

As many mentioned, there are multiple ways to do this, most noticable are these 4 methods:

function swap1(&$x, &$y) {
// Warning: works correctly with numbers ONLY!
$x ^= $y ^= $x ^= $y;
}
function swap2(&$x, &$y) {
list($x,$y) = array($y, $x);
}
function swap3(&$x, &$y) {
$tmp=$x;
$x=$y;
$y=$tmp;
}
function swap4(&$x, &$y) {
extract(array('x' => $y, 'y' => $x));
}

I tested the 4 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. Winner!
  • swap4() = scored approximate average of 0.73 seconds.

And for readability, I find swap3() is better than the other functions.

Note

  • swap2() and swap4() are always slower than the other ones because of the function call.
  • swap1() and swap3() both performance speed are very similar, but most of the time swap3() is slightly faster.
  • Warning: swap1() works only with numbers!

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

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.

$a = 'ravi';


$b = 'bhavin';


$a = $b.$a;


$b = substr($a,strlen($b),strlen($a));


$a = substr($a,0,strlen($a)-strlen($b));


echo "a=".$a.'<br/>'.'b='.$b;
<?php


swap(50, 100);


function swap($a, $b)
{
$a = $a+$b;
$b = $a - $b;
$a = $a - $b;
echo "A:". $a;
echo "B:". $b;
}
?>

I checked all solutions after that i came up with another solution that was not found anywhere. my logic is simple. i used PHP variable ref. pattern. means $$. you can read more about this by this link https://www.php.net/manual/en/language.variables.variable.php

$a =12;$b="ABC";
$$a =$b;
$$b= $$a.$a;
echo " a = $a and b=$b <br>now after reverse.<br>";
echo $$b;

//output : abc12