<!–Swapping two number without using third variable–>
$a = 3;
$b = 2;
echo “Before swapping a and b : $a, $b”.”<br/>”;
$a = $a+$b; // value of $a now is 5
$b = $a-$b; // value of $b now is 3
$a = $a-$b; // value of $a now is 2
echo “After swapping a and b : $a, $b”;
This is one of the simple logic questions asking in the freshers interview.
Usually we used to swap two variables using the third temporary variable.
Here we assigned $a itself a temporary varible. So that we don’t need third one.
Here what the logic is assign $a’s or $b’s value to one place.
ie) $a=3; $b=2; $a= $a+$b;
Now $a is 5 (logic goes here)
Using the $a value 5, we can start swapping $a & $b in the above manner.