Swapping Two variables

Swapping in PHP is a very easy method. Swapping two variables means you have to interchange the value of variables. Let's learn with an example, we create two variables like $x and $y and assign the values. Here, we create a simple mathematical logic for swapping two variables. There is no swap function in PHP.

You have to create a logic according to the task using variables. After the PHP script executed the value of $x will be changed by the value of $y and the value of $y will be changed by value $x.

Swapping Two variables by creating a simple mathematical logic using PHP

Before the swapping-
After the swapping –
Before the swapping, the value of $x is 4 and the value of $y is 5 .
After the swapping, the value of $x will be 5(that was the value of $y) and the value of $y will be 4 .


echo "Before swap Value of x & y :".$x."      ".$y."
"; $y=$x+$y; $x=$y-$x; $y= $y-$x; echo "After swap value of x & y:".$x." ".$y; ?>

Swapping two variables using list() and array()

In the above example, we have not used any function of PHP but we also use the array() function to swap two variables. In this example, we also use the list() . Like array (), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation. By using the list and arrays, we can swap variables easily.Let's implement the program.


$a = "Hello";
$b = "Yes";

echo 'Before swap:-'.'
'; echo 'After swap:-
'; list($a, $b) = array($b, $a); echo 'A='.$a; echo '
'; echo 'B='.$b; ?>



Before swap:-
After swap:-

In the above example, we create two variables. After swapping, the value of the first variable is stored in the second variable. Similarly, after swapping the second variable value is stored in the first variable. This is known as the process of value interchanging. This is called the swapping of two variables.

Please Share

Recommended Posts:-