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

前端 未结 19 855
终归单人心
终归单人心 2020-12-02 08:36

Say for instance I have ...

$var1 = \"ABC\"
$var2 = 123

and under certain conditions I want to sw

相关标签:
19条回答
  • 2020-12-02 08:44
    <?php
    
    swap(50, 100);
    
    function swap($a, $b) 
    {
       $a = $a+$b;
       $b = $a - $b;
       $a = $a - $b;
       echo "A:". $a;
       echo "B:". $b;
     }
    ?>
    
    0 讨论(0)
  • 2020-12-02 08:45

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

    0 讨论(0)
  • 2020-12-02 08:49

    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/

    0 讨论(0)
  • 2020-12-02 08:53

    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;
    
    0 讨论(0)
  • 2020-12-02 08:54

    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!
    0 讨论(0)
  • 2020-12-02 08:54

    Another way:

    $a = $b + $a - ($b = $a);
    
    0 讨论(0)
提交回复
热议问题