是否有一个用于交换两个变量值的PHP函数? [英] Is there a PHP function for swapping the values of two variables?

查看:183
本文介绍了是否有一个用于交换两个变量值的PHP函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



说例如我有...

$ var1 =ABC
$ var2 = 123

在特定条件下,我想交换两个像这样...

  $ var1 = 123 
$ var2 =ABC

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


$ b

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

简单的任务它可能更快地使用第三个变量,我总是可以创建自己的功能,如果我真的想。只是想知道是否存在类似的东西?



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

解决方案

没有内置函数。



正如很多人所说,有3种方法可以做到这一点:

 函数swap1(& $ x,& $ y){ 
$ x ^ = $ y ^ = $ x ^ = $ y;

函数swap2(& $ x,& $ y){
list($ x,$ y)= array($ y,$ x);
}
函数swap3(& $ x,& $ y){
$ tmp = $ x;
$ x = $ y;
$ y = $ tmp;
}

我在1000次迭代的for循环下测试了3种方法,它们中速度最快:


  • swap1 =得分的近似平均值 0.19 秒。

  • swap2 =得分的近似平均值为0.42秒。

  • swap3 = 0.16分钟的近似平均值。


为了可读性/可写性,IMO发现swap3比其他两个函数要好。

更新2017:




  • swap2总是比其他类型的因为函数调用而慢。

  • swap1和swap3的性能速度非常相似,但大多数情况下,swap3的速度稍快。

  • 警告: swap1仅适用于数字!


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.

解决方案

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) {
    $tmp=$x;
    $x=$y;
    $y=$tmp;
}

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.

UPDATE 2017:

  • swap2 is 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!

这篇关于是否有一个用于交换两个变量值的PHP函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆