How to interchange 2 variables? A simple question with a simple answer. Most people will do it like this:
// interchanging using a temporary variable $a = 2; $b = 3; $temp = $a; $a = $b; $b = $temp; echo $a . ' ' . $b . PHP_EOL; // will display 3 2
Quite elementary. But it can be done in a much more elegant manner, using arithmetical (addition & subtraction) or logical (xor) operators.
First of all, let’s interchange the variables using addition and subtraction. The code will look like this:
// arithmentical operations $a = 2; $b = 3; $a = $a + $b; // a = 5, b = 3 $b = $a - $b; // a = 5, b = 2 $a = $a - $b; // a = 3, b = 2 echo $a . ' ' . $b . PHP_EOL;
…or, in a more “hacker” style…
// arithmetical operations - one line $a = 2; $b = 3; $a = $a + $b - ( $b = $a ); echo $a . ' ' . $b . PHP_EOL;
But variable interchange can also done using the XOR operator. This is also supposed to be the fastest way.
// xor $a = 2; // 10 (in binary) $b = 3; // 11 (in binary) $a = $a ^ $b; // a = 01, b = 11 $b = $a ^ $b; // a = 01, b = 10 $a = $a ^ $b; // a = 11, b = 10 echo $a . ' ' . $b . PHP_EOL;
Again, one line variable interchange, this time using xor.
// xor - one line $a = 10; $b = 5; $a = $a ^ $b ^ ( $b = $a ); echo $a . ' ' . $b . PHP_EOL;
What are these good for? Well, let’s see, you can post them on your blog late at night when you’re not sleepy and pretend you know everything. Of course, this isn’t my case, since is not *that* late at night.
I like the reason for which these tricks are good for
. Anyway, the bitwise versions are hard to understand as a first glance, so inspired by a JavaScript 1.7 feature I discovered a new and simpler way to do it in PHP.
$a = 1;
$b = 2;
list($a, $b) = array($b, $a);
That’s all, and you’re more likely to understand what it does.
P.S. The JavaScript 1.7 feature I was talking about is called “destructuring assignment” [1] and is in turn inspired from Python (which I have no idea where they got the inspiration).
[1] https://developer.mozilla.org/en/New_in_JavaScript_1.7#Destructuring_assignment
But that’s kind of expensive, although it’s a nice trick, it’s more expensive than using a third variable. Xor is really fast, but only works on integers.
Using list($a, $b) = array($b, $a); for variable interchange it’s like killing a fly with an atomic bomb!
) =))
That IS NOT a solution!
It’s a cool trick, non the less…
Define “cool”.
If “cool” means too much overhead added, than yes, it is cool!
Speed it is the most important thing! How can you achieve speed with useless overhead added?
Raul, I have watched several courses on MIT’s OCW. One of them was Introduction to Algorithms. The professor specifically stated that in an algorithm/program, the most important thing is code readability, seconded by performance (speed, memory allocation, stability, robustness).
And he is so right! Would you be able to customize the fastest algorithm ever for let’s say sorting an array if you don’t comprehend it or an algorithm that is not as fast but is more readable?
Keep in mind the fact that I am talking about algorithms, not variable interchange…
Yes, I think I know what you mean!
Still, readability can be achieved by adding comments, after all, isn’t it?
Nope. Comments are useful when all the functionality in encapsulated in a function or a method of class. You’ll have something like:
Due to the comments and phpdoc tags, this function would be easy to use. You know what it does. But when you need to change the “content” of the function or how it does its stuff, code readability is a very important issue.
And beside, writing 3 lines of comments after each line of code just because you wanted to try an “elegant” and “original” approach is lame…
Writing 3 lines or even 300 lines of comments where it is needed it’s a good ideea!
Raul, I have to disagree with you for a couple of reasons:
1. That trick is slower than a temporary variable, but the time required to execute that assignment probably takes less than is needed for a fly to flip its wings once.
2. Following the same logic, objects and functions are probably bad because they introduce overhead, while simple global code does not.
There is a threshold when you really have to care about such optimizations, most likely after optimizing database access and heavy algorithms.
Also, comments are best for user programmers (by generating documentation from phpdoc comments), who want to use a certain library but don’t want to dive the source code. Additionally, comments *must* be used for hard to understand algorithms. Regardless of the above though, the API should talk for itself.
Finally, a temporary variable is probably the way to go, every PHP newbie would understand such a piece of code, but as the “overhead” introduced is so small it basically becomes a matter of taste. As it is with echo vs. print and single quotes vs. double quotes.
Btw, in Python (I am a big Python fan) you would just write
a, b = b, a
How cool is that?
I have to agree that that’s pretty neat…
You can do that with any data structure in Python (simple variable, lists, tuples, dictionaries).
I’ve got it! You can interchange variables in this manner in python and in php you cannot. Now get over it…
Sore loser?!
Just saw what Radu said…
Radu, that is basically the same thing as the list/array solution in PHP. Python though, has the advantage of some syntactic sugar for declaring tuples, so one doesn’t have to write the parens. That’s all. Is there a bigger difference and I’m not yet seeing it?