DEV Community

Fajar Windhu Zulfikar
Fajar Windhu Zulfikar

Posted on • Originally published at fajarwz.com on

Swap Two Variables Value Without Temp Variable in PHP

Swap things illustration

Maybe you find a real world project situation that you think maybe it’s good for you to know how to swap two variables without temporary variable for example for clean coding. Or maybe you are just trying to solve some kind of online coding test that force you to trying to do swap between two variables without third variable.

Is there a PHP function for doing that rather than having to create third variable for such a simple task?

PHP Array Destructuring

Meet this array destructuring syntax. Available since PHP 7.1.

[$a, $b] = [$b, $a];
Enter fullscreen mode Exit fullscreen mode

An example with output

<?php

$a = 'foo';
$b = 'bar';

echo "Original value: $a, $b\n"; // Original value: foo, bar

[$a, $b] = [$b, $a];

echo "Result value: $a, $b\n"; // Result value: bar, foo
Enter fullscreen mode Exit fullscreen mode

That's it. I hope it helpful.

Conclusions

What you need for swapping variable without temp variable in PHP is array destructuring. I think it looks cleaner.

Any thought on this approach? Please let me know in the comments section below. Thank you.

References

Is there a PHP function for swapping the values of two variables? | Stackoverflow | Answer by Pawel Dubiel

Top comments (0)