How to SWAP values of two variables without using a third variable?

1. Arithmetic operation
2. Bitwise operation.

Arithmetic Operation:

Bitwise operation:
x = x XOR y
y = x XOR y
x = x XOR y
if we write them in computer language using caret (^) then it will look like

x = x ^ y
y = x ^ y
x = x ^ y

in shorter version:

x ^= y
y ^= x
x ^= y

in one line

x ^= y ^= x ^= y

so here is the command in php:

$x ^= $y ^= $x ^= $y

This is collected from http://www.mizanurrahman.com/2008/07/30/how-to-swap-values-of-two-variables-without-using-a-third-variable. You can get more details about these operation on his blog.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s