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

前端 未结 19 858
终归单人心
终归单人心 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:03
    $a=5; $b=10; $a=($a+$b)-$a; $b=($a+$b)-$b;
    
    0 讨论(0)
  • 2020-12-02 09:04
    list($var1,$var2) = array($var2,$var1);
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-02 09:04

    another answer

    $a = $a*$b;
    $b = $a/$b;
    $a = $a/$b;
    
    0 讨论(0)
  • 2020-12-02 09:08

    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.

    0 讨论(0)
  • 2020-12-02 09:09

    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;
        ?>
    
    0 讨论(0)
提交回复
热议问题