Swap Variable’s Values in PHP

Google+ Pinterest LinkedIn Tumblr +

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;
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.


About Author

Leave A Reply