note 90859 deleted from function.list by googleguy
| From: | googleguy@php.net | Date: | Thu, 13 Sep 2012 10:03:13 +0000 |
| Subject: | note 90859 deleted from function.list by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-190696@lists.php.net to get a copy of this message | ||
Note Submitter: claude dot pache at gmail dot com
----
A simple way to swap variables (correction of a note of mario dot mueller dot work at gmail dot com
below):
<?php
list($var1, $var2) = array($var2, $var1); // swaps the values of $var1 and $var2
?>
Note that this is not equivalent to:
<?php
$var2 = $var1; $var1 = $var2; // $var1 and $var2 get both the old value of $var1
?>
as one could fear. Indeed, the array is constructed with the values of $var1 and $var2 (and not with
the variables $var1 and $var2 themselves) before the assignment is carried out.
Similarly, it is possible to bypass the problem pointed by sasha in the previous note by providing
an expression rather than a variable on the right-hand side of the assignment operator:
<?php
$var = array ("test" ,"blah");
list ($a,$var) = $var + array();
echo $a ; // prints "test", not "b"
echo $var ; // prints "blah"
?>