1.3 Swapping Variables


1.3 Swapping Variables

You want to swap the values of two variables, but you don't want to use a temporary variable.

Technique

Use the list() and array() constructs to switch the variables:

 <?php list ($var1, $var2) = array ($var2, $var1); ?> 

Comments

In many other languages, you must use a temporary variable, like so:

 <?php $temp = $var1; $var1 = $var2; $var2 = $temp; ?> 

However, in PHP, the list() construct does this for you. The list() construct is used to assign a list of variables, and it is used for more than just swapping variables. You can also use it for processing arrays, as shown here:

 <?php $items = array ("Linux",                 "Apache",                 "PHP",                 "A SQL Server",                 "Talented Administrator"); print "The essentials for operating your own webserver:\n"; reset ($items); while (list (, $item) = each ($items)) {     print "$item\n"; } ?> 

Gotcha

Note that the actual syntax in the preceding example is list(, $item) ; the comma is there to denote that there is another element in the array (the numerical index of the item) we are processing. It is important to keep in mind that each() returns the item index as well as the item when dealing with numerically indexed arrays.




PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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