Swap Two Variables Value Without Temp Variable in PHP

Updated
featured-image.png

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

Fajarwz's photo Fajar Windhu Zulfikar

I'm a full-stack web developer who loves to share my software engineering journey and build software solutions to help businesses succeed.

Email me
Ads
  • Full-Stack Laravel: Forum Web App (Complete Guide 2024)
  • Flexible and powerful review system for Laravel, let any model review and be reviewed.

Share

Subscribe

Sign up for my email newsletter and never miss a beat in the world of web development. Stay up-to-date on the latest trends, techniques, and tools. Don't miss out on valuable insights. Subscribe now!

Comments

comments powered by Disqus