Swap Two Variables Value Without Temp Variable in PHP | Fajarwz

Fajarwz
2 min readJun 19, 2022

--

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];

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

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

Originally published at https://fajarwz.com on June 19, 2022.

--

--

Fajarwz
Fajarwz

No responses yet