Robson » Little Red Book » Swap

Chapter 2 - Question 8

Given two variables, A and B say, exchange their values so that A has the previous value of B and B has the previous value of A.

Solution 1

The simple solution is to use a third variable:

<?
   // set values for the variables
   $a = 3;
   $b = 7;
   
   // save a to a new variable called c
   $c = $a;
   // a is now stored somewhere else, so override it with b
   $a = $b;
   // b is now stored in a, so update that to c
   $b = $c;
   
   // output the variables
   echo 'A = ' . $a . ', B = ' . $b;    
?>

Which produces:

A = 7, B = 3

Log

© 2004-17 robson | cc unless stated