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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3541730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:09:39  来源:igfitidea点击:

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

phpfunctionswap

提问by Taylor

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

是否有一个 PHP 函数可以执行此操作,而不必创建第三个变量来保存其中一个值,然后重新定义每个值,就像这样......

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

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

Update: Using a 3rd variable or wrapping it in a function is the best solution. It's clean and simple. I asked the question more out of curiosity and the answer chosen was kind of 'the next best alternative'. Just use a 3rd variable.

更新:使用第三个变量或将其包装在函数中是最好的解决方案。它干净而简单。我更多是出于好奇而问这个问题,所选择的答案是“次佳选择”。只需使用第三个变量。

回答by evilReiko

TL;DR

TL; 博士

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

没有内置函数。swap3()如下所述使用。

Summary

概括

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

正如许多人提到的,有多种方法可以做到这一点,最值得注意的是这 4 种方法:

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:

我在 1000 次迭代的 for 循环下测试了 4 种方法,以找到其中最快的:

  • swap1()= scored approximate average of 0.19seconds.
  • swap2()= scored approximate average of 0.42seconds.
  • swap3()= scored approximate average of 0.16seconds. Winner!
  • swap4()= scored approximate average of 0.73seconds.
  • swap1()= 平均得分为0.19秒。
  • swap2()= 平均得分为0.42秒。
  • swap3()= 平均得分为0.16秒。优胜者!
  • swap4()= 平均得分为0.73秒。

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

对于可读性,我发现swap3()它比其他功能更好。

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!
  • swap2()swap4()由于函数调用,并且总是比其他的慢。
  • swap1()并且swap3()两者的性能速度非常相似,但大部分时间swap3()都稍快一些。
  • 警告:swap1()仅适用于数字!

回答by Pekka

There's no function I know of, but there is a one-liner courtesy of Pete Graham:

我不知道有什么功能,但有一个由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.

此外,正如@Paul Dixon 指出的那样,它效率不高,而且比使用临时变量的成本更高。在一个非常大的循环中可能值得注意。

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?

然而,无论如何,这种必要的情况对我来说有点不对劲。如果你想讨论它:你需要这个做什么?

回答by Pawel Dubiel

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:

是的,现在存在这样的东西。它不是函数而是语言结构(自 PHP 7.1 起可用)。它允许这个简短的语法:

 [$a, $b] = [$b, $a];

See "Square bracket syntax for array destructuring assignment"for more details.

有关更多详细信息,请参阅“数组解构赋值的方括号语法”

回答by Pawel Dubiel

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

也可以使用旧的 XOR 技巧(但是它仅适用于整数,并且不会使代码更易于阅读......)

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

回答by Justin Ethier

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:

这让我想起了 python,这样的语法是完全有效的:

a, b = b, a

It's a shame you can't just do the above in PHP...

很遗憾你不能只在 PHP 中执行上述操作...

回答by Prasanth

Another way:

其它的办法:

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

回答by Naga Krishna Teja Komma

For numbers:

对于数字:

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

Working:

在职的:

Let $a = 10, $b = 20.

让 $a = 10, $b = 20。

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

$a = $a+$b(现在,$a = 30,$b = 20)

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

$b = $a-$b(现在,$a = 30,$b = 10)

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

$a = $a-$b(现在,$a = 20,$b = 10 交换!)

回答by Ron van der Heijden

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

工作示例:http: //codepad.viper-7.com/ytAIR4

回答by user2907171

another simple method

另一种简单的方法

$a=122;
$b=343;

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

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

回答by Thomas Clayson

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