Exchanging Values without Using Temporary Variables

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

Posted on March 12, 2015 in PHP

To Swap $a and $b:

$a = 'Alice';
$b = 'Bob';
list($a, $b) = array($b, $a);

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 tow values.

comments powered by Disqus