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

前端 未结 19 918
终归单人心
终归单人心 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 09:04

    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

提交回复
热议问题