Search code examples
phpoperators

Is it safe to use xor for variable swapping in PHP


Is it safe to use this kind of variable swapping in php ?

$a^=$b^=$a^=$b;

Solution

  • No, because the variables may not be types that can be XORd the way you expect. The PHP idiom for swapping two variables (of any scalar type) in one line is:

    list($a, $b) = array($b, $a);
    

    Or simply:

    [$a, $b] = [$b, $a];