PHP 有没有可以交换两个变量值的函数?

发布于 2024-09-15 10:58:33 字数 563 浏览 9 评论 0原文

举例来说,我有...

$var1 = "ABC"
$var2 = 123

并且在某些条件下我想像这样交换这两个...

$var1 = 123
$var2 = "ABC"

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

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

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

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

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?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

半边脸i 2024-09-22 10:58:33

TL;DR

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

总结

正如许多人提到的,有多种方法可以做到这一点,最值得注意的是这 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));
}

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

  • swap1() = 得分大约为 0.19 秒的平均值。
  • swap2() = 得分约为 0.42 秒的平均值。
  • swap3() = 得分约为 0.16 秒的平均值。 获胜者!
  • swap4() = 得分大约为 0.73 秒。

为了可读性,我发现 swap3() 比其他函数更好。

注意,

  • 由于函数调用,swap2()swap4() 总是比其他函数慢。
  • swap1()swap3() 两者的性能速度非常相似,但大多数时候 swap3() 稍快一些。
  • 警告: swap1() 仅适用于数字!

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!
蓝天白云 2024-09-22 10:58:33

我不知道有什么功能,但有一个由 Pete Graham

list($a,$b) = array($b,$a);

不过,不确定从维护的角度来看我是否喜欢这个,因为它并不是很直观地理解。

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

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

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?

地狱即天堂 2024-09-22 10:58:33

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

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

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

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.

北座城市 2024-09-22 10:58:33

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

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

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;
最舍不得你 2024-09-22 10:58:33

是的,尝试 这个

// Test variables
$a = "content a";
$b = "content b";

// Swap $a and $b
list($a, $b) = array($b, $a);

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

a, b = b, a

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

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

梦罢 2024-09-22 10:58:33

对于数字:

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

工作:

设$a = 10,$b = 20。

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

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

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

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

七色彩虹 2024-09-22 10:58:33

另一种方式:

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

Another way:

$a = $b + $a - ($b = $a);
删除会话 2024-09-22 10:58:33
list($var1,$var2) = array($var2,$var1);
list($var1,$var2) = array($var2,$var1);
吻风 2024-09-22 10:58:33

这个速度更快,需要的内存更少。

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

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

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

烂柯人 2024-09-22 10:58:33

另一种简单的方法

$a=122;
$b=343;

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

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

another simple method

$a=122;
$b=343;

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

echo '$a='.$a.PHP_EOL;
echo '$b='.$b;
权谋诡计 2024-09-22 10:58:33

这是另一种不使用临时变量或第三个变量的方法。

<?php
$a = "One - 1";
$b = "Two - 2";

list($b, $a) = array($a, $b);

echo $a . $b;
?>

如果你想让它成为一个函数:

    <?php
    function swapValues(&$a, &$b) {
         list($b, $a) = array($a, $b);
     }
    $a = 10;
    $b = 20;
    swapValues($a, $b);

    echo $a;
    echo '<br>';
    echo $b;
    ?>

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;
    ?>
辞慾 2024-09-22 10:58:33

感谢您的帮助。我已将其变成 PHP 函数 swap()

function swap(&$var1, &$var2) {
    $tmp = $var1;
    $var1 = $var2;
    $var2 = $tmp;
}

代码示例可以在以下位置找到:

http://liljosh .com/swap-php-variables/

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/

哑剧 2024-09-22 10:58:33

3 个选项:

$x ^= $y ^= $x ^= $y; //bitwise operators

或:

list($x,$y) = array($y,$x);

或:

$tmp=$x; $x=$y; $y=$tmp;

我认为第一个选项是最快的并且需要较少的内存,但它不适用于所有类型的变量。 (示例:仅适用于具有相同长度的字符串)
不管怎样,这个方法无论从哪个角度来说都比算术方法要好得多。
(算术:{$a=($a+$b)-$a; $b=($a+$b)-$b;} MaxInt 问题,等等...)

函数例如:

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

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);
仙女 2024-09-22 10:58:33

如果两个变量都是整数,您可以使用数学方法:

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

很好的博客文章 - http://booleandreams.wordpress.com/2008/07/30/how-to-swap-values-of-two-variables-without-using -第三个变量/

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/

甜柠檬 2024-09-22 10:58:33

是的,我知道有很多可用的解决方案,但这是另一种。
您也可以使用 parse_str() 函数。参考W3Schools PHP parse_str() 函数

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

?>

演示

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

烟花肆意 2024-09-22 10:58:33

我检查了所有解决方案后,我想出了另一个在任何地方都找不到的解决方案。我的逻辑很简单。我使用了 PHP 变量引用。模式。意思是$$。您可以通过此链接阅读更多相关信息 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

如果你不想使用该方法那么你也可以尝试这个

$a =10; $b=15;

echo  " a = $a , b= $b \n";  // a= 10 , b=15

$a = $a ^ $b; echo "a= 5 \n" ;
$b = $a ^ $b; echo "b= 10 \n" ;
$a = $a ^ $b; echo "a= 15 \n" ;

echo  " a = $a , b= $b";  // a= 15 , b=10

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

If you do not want to use the method then you can try this also

$a =10; $b=15;

echo  " a = $a , b= $b \n";  // a= 10 , b=15

$a = $a ^ $b; echo "a= 5 \n" ;
$b = $a ^ $b; echo "b= 10 \n" ;
$a = $a ^ $b; echo "a= 15 \n" ;

echo  " a = $a , b= $b";  // a= 15 , b=10
东风软 2024-09-22 10:58:33
$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;
$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;
ぃ弥猫深巷。 2024-09-22 10:58:33

另一个答案

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

another answer

$a = $a*$b;
$b = $a/$b;
$a = $a/$b;
dawn曙光 2024-09-22 10:58:33
<?php

swap(50, 100);

function swap($a, $b) 
{
   $a = $a+$b;
   $b = $a - $b;
   $a = $a - $b;
   echo "A:". $a;
   echo "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;
 }
?>
清君侧 2024-09-22 10:58:33
$a=5; $b=10; $a=($a+$b)-$a; $b=($a+$b)-$b;
$a=5; $b=10; $a=($a+$b)-$a; $b=($a+$b)-$b;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文