DEV Community

Discussion on: How can you swap two variables without using a third?

Collapse
jjjjcccjjf profile image
endan
function swap (&$a, $b, $A) {
    $a = $b;
    return $A;

} 

$a = 7;
$b = 9;

$b = swap($a, $b, $a);

echo "a is " . $a; # 9
echo "b is " . $b; # 7

/* scratches head again */
Collapse
gmartigny profile image
Guillaume Martigny

As funny as it is, you declare a new pointer to the swap function allocating new memory.

Collapse
svenluijten profile image
Sven Luijten
// Since PHP 7.1:
[$b, $a] = [$a, $b];

// Or before 7.1:
list($b, $a) = [$a, $b];