1.3 Swapping Variables
TechniqueUse the list() and array() constructs to switch the variables: <?php list ($var1, $var2) = array ($var2, $var1); ?> CommentsIn 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. |