Recipe 5.3. Exchanging Values Without Using Temporary Variables


5.3.1. Problem

You want to exchange the values in two variables without using additional variables for storage.

5.3.2. Solution

To swap $a and $b:

list($a,$b) = array($b,$a);

5.3.3. Discussion

PHP's list( ) language construct lets you assign values from an array to individual variables. Its counterpart on the right side of the expression, array( ), lets you construct arrays from individual values. Assigning the array that array( ) returns to the variables in the list( ) lets you juggle the order of those values. This works with more than two values, as well:

list($yesterday,$today,$tomorrow) = array($today,$tomorrow,$yesterday);

This method isn't faster than using temporary variables, so you should use it for clarity, but not speed.

5.3.4. See Also

Documentation on list( ) at http://www.php.net/list and array( ) at http://www.php.net/array.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net