在PHP中的两个变量的值之间进行替换

在PHP中的两个变量的值之间进行替换

问题描述:

I was wondering if it could be possible to make a substitution between the values of two variables, in PHP.

I can explain it better:

<?php
    $a = "Cat";
    $b = "Dog";

    // The strange/non-existent function I am talking about //
    MakeSubstitution($a, $b);

    // After this (non-existent) function the values of the variables should be:
        // $a = "Dog"
        // $b = "Cat"
?>

So, does it exist? I made searches but I found no results. Thanks in advance.

Try this :

$a = "Cat";
$b = "Dog";

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

echo $a;
echo $b;

Handle them by reference in a function, and swap their values:

function swap ( &$a, &$b ) {
    $t = $a; // Create temp variable with value of $a
    $a = $b; // Assign to $a value of $b
    $b = $t; // Assign to $b value of temp variable
}

$dog = "dog";
$cat = "cat";

swap($dog, $cat);

echo $dog; // Output 'cat'

Apparently you can use a bitwise operator too, and avoid the overhead of creating a temporary function/var/array:

$cat = "cat";
$dog = "dog";

$cat = $cat ^ $dog;
$dog = $cat ^ $dog;
$cat = $cat ^ $dog;

echo $cat . $dog; // Output 'dogcat'

Managed to find a great illustration of the bitwise approach: https://stackoverflow.com/a/528946/54680