4

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.

w5m
  • 2,286
  • 3
  • 34
  • 46
robytur
  • 97
  • 1
  • 8
  • `function MakeSubstitution($a,$b) { $t = $a; $a = $b; $b = $a }`. Done? – Brad Christie Mar 06 '13 at 13:27
  • 1
    You want to swap the values of two variables? What is a use case for this? Write your own method (look at Brad Christie above - don't forget to accept the variables as references if you want to modify them) in the scope of the caller – Colin M Mar 06 '13 at 13:28
  • You seriously expect a function for such a trivial problem? Man, just wait until things get complicated and you have to write your own 200+ lines algorithm. – Shoe Mar 06 '13 at 13:30
  • I know a few lines of code are enough, but as you know, PHP is going to simplify simple things and I thought there was a function for that. No problem... – robytur Mar 06 '13 at 13:41

2 Answers2

16

Try this :

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

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

echo $a;
echo $b;
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
  • 2
    This is definitively my favourite answer, because the "function" stays only in one line. Thanks to the others too. – robytur Mar 06 '13 at 13:42
6

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

Community
  • 1
  • 1
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • 1
    This is actually the answer that should be accepted. No array, no other functions, just plain assignments. This is possibly the fastest too. – Shoe Mar 06 '13 at 13:32
  • Yes this is the function that describes exatly what I need to do. The only disadvantage is that you need to write the function. – robytur Mar 06 '13 at 13:39