PHP: 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 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-
$x=4;
$y=5;
After the swapping –
$x=5;
$y=4;
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 .

Example

<?php
$x=4;
$y=5;
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; ?>
Run

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.

Example

<?php
$a = "Hello";
$b = "Yes";

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

Output

 

Before swap:-
A=Hello
B=Yes
After swap:-
A=Yes
B=Hello

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 swapping of two variables.