In this post, let’s write a simple PHP snippet to swap two variables without using a temporary variable. Basically, we are going to declare two variables x and y and then swap the values of x and y without introducing a 3rd variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php //let's declare variables $x = 100; $y = 200; print 'Origin value of x and y is ' . $x . ' & ' . $y . '<br>'; print '<br>After swapping: <br>'; //now swap the values without introducing a 3rd variable list($x, $y) = array($y, $x); print 'Swapped value of x and y is ' . $x . ' & ' . $y; ?> |
Sample output of the above program is here,