Archive for the ‘Variables’ Category

Swapping variables without using temporary variable

Thursday, October 11th, 2007

For example we wanted to swap two variable values given

$x = 10;
$y = 20;

The usual way of exchanging their variables is to use a temporary variable like the one below

$x = 10;
$y = 20;
$z = $x; // $z will be equal to 10 now which will serve as a temporary variable
$x = y; // $x will be equal to 20 now
$y = $z; // $y will be 10 now

Their is another way to do this without using temporary variable is the use of list() function

$x = 10;
$y = 20; 
list($x, $y) = array($y, $x);

You can also do this in multiple variables

$sDog1 = "Boston Terrier";
$sDog2 = "American Bulldog";
$sDog3 = "German Shepperd";
$sDog4 = "Great Dane";
list($sDog1, $sDog2, $sDog3, $sDog4) = array($sDog3, $sDog1, $sDog4, $sDog2);