Swap two variables

Shows how to swap two variables without using a temporary variable.

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
12/05/2007

Updated:
12/05/2007

Tags:
,


// Test variables
$a = "content a";
$b = "content b";
 
// Swap $a and $b
list($a, $b) = array($b, $a);
 
// Debug print
print "variable a: $a\n";
print "variable b: $b\n";
 
/*
Output:
 
variable a: content b
variable b: content a
*/


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

sundar August 20, 2010 at 15:57
that code is used to noe time excute.but another did not change.so please help me
shital July 15, 2010 at 12:13
It's excellent ...... :)
thank u for help
Bharanikumar July 02, 2010 at 19:09
Is it possible with array and swaping with only one variable ,
Robc July 18, 2009 at 19:06
Oh, so very simple and nice. Thank you!
TecBrat July 08, 2009 at 18:56
Excellent!
I am using it to test image dimensions HxW or WxH, but that seems like it could really speed up a bubble sort.

Thanks.
josepzin June 13, 2009 at 13:59
Very nice, Thanks :)
Werner February 12, 2009 at 16:13
Very cool! ;)
Oscuro January 19, 2009 at 10:32
Thanks, very cute!
Tom August 22, 2008 at 18:33
Great, Thanks!