PHP program to swap two variables without a 3rd variable

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.

<?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,

phpswap

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top