Swap Variable's Values in PHP

Feb 5th, 2009 by web-development

In this tutorial you will learn how to quickly and simply swap the values of 2 variables in just 1 line of code without using a third variable temporarily. This article is demonstrated in PHP although the same principle applies to other languages such as C and C++.

Most people never come across the problem of having to swap the value of 2 variables, but at some point you may encounter the need to do so quickly and efficiently.

Where some would accept using a 3rd variable to do the swapping of values, others are thinking whether it is possible to do this using a more efficient method.

The following is an example demonstrates how to swap the value of 2 variables using a 3rd temporary variable:

old_value = 1
new_value = 2
temp_value = 3

temp_value = old_value
old_value = new_value
new_value = temp_value

In PHP this would look like:

$old_value = 1;
$new_value = 2;
$temp_value = NULL; $temp_value = $old_value;
$old_value = $new_value;
$new_value = $temp_value;
unset($temp_value); echo $old_value; // outputs 2
echo $new_value; // outputs 1

That is some code just to swap the value of 2 variables. Without going into detail on how it works, the Exclusive Or (XOR) operator can be used to simplify this task.

The above example in PHP can simply be replaced using the following:

$old_value ^= $new_value ^= $old_value ^= $new_value;

If you look closely, you will even notice that a 3rd variable has not been used.

To make the task of swapping variable values even simpler, you can also create your own function for doing so:

function swap (&$x, &$y) {
$x ^= $y ^= $x ^= $y;
}

There you have it, swapping 2 variable's values in 1 simple line of programming.

web-development

Written by web-development

Rate this Article:

Rating: 5.0/5 (1 votes cast)

Add new comment

* You must be logged in order to leave comments, please Sign in or join us.

Comments

Report comment

This program tell us how to swap array value. Array swap sample : ‘one’); $y = array(‘b’ => ‘two’);

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

echo ‘X : ‘; print_r($x); echo ‘Y : ‘; print_r($y); ?>

Output: X : Array ( [b] => two ) Y : Array ( [a] => one )

Class swap : <?php

class a { public $name = ‘alu’; } class b { public $name = ‘begun’; }

$x = new a(); $y = new b();

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

echo ‘X : ‘; var_dump($x); echo ‘Y : ‘; var_dump($y); ?>

psix, over a year ago
Report comment

Nice try!
But when i tested it, i saw that it only works with numbers not to big and it doesn’t work with strings of different length; i think this one list($b,$a) = array($a,$b); i found somewhere else does a much better job!