DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,904 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in

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

Collapse
 
jjjjcccjjf profile image
ο½…ο½Žο½„ο½ο½Ž
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];