Swap two variables in PHP
A very simple post, with a very simple solution to a very simple problem.
Sometimes you will need to swap two variables around, perhaps if you have a form that asks the user to enter minimum and maximum values for something, and they accidentally enter the larger value in the minimum box and vice versa.
The old school, basic way to do it is like this:
$temp = $var1; $var1 = $var2; $var2 = $temp;
However in PHP there is a quicker, more elegant way to do it, that doesn’t use a temporary variable:
list( $var1, $var2 ) = array( $var2, $var1 );
I told you it was simple. If you’re not sure you understand what is going on, read about the list function in the PHP online documentation.