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

前端 未结 19 928
终归单人心
终归单人心 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:55

    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?

提交回复
热议问题