PHP Program to swapping variables without temporary variable

What is the swapping of two variables?

In this program, we are swapping two variables using PHP. Swapping is meant by interchanging the values of the variables. For example, if the user entered 5 into the first variable and 6 into the second variable after swapping the value of the first variable will be 6 and the value of the second variable will be 5.

How to swap the variables without using temporary variable using PHP?

In this program, we are accepting the values from the user. First, we have to read the values from the user and store the values into the variables num1 and num2. After that, we assign the computed value of 'num1 + num2' into the variable num1 then we have to assign the computed value of 'num1 - num2' into the variable num2 then we have to assign the computed value of 'num1 - num2' into the variable num1. After the completion of these operations, we have to print the values of num1 and num2 as swapped.

ALGORITHM

Step 1: Accept the numbers into the variables num1 and num2

Step 2: Print the values of variables num1 and num2 as before swapping values

Step 3: Assign the computed value of 'num1 + num2' into the variable num1

Step 4: Assign the computed value of 'num1 - num2' into the variable num2

Step 5: Assign the computed value of 'num1 - num2' into the variable num1

Step 6: Print the values of variables num1 and num2 as swapped values

PHP Source Code

                                          <?php
$num1 = readline("Enter the first number: ");
$num2 = readline("Enter the second number: ");
echo "Before Swapping \n First Number = $num1 \n Second Number = $num2 \n";
$num1 = $num1 + $num2;
$num2 = $num1 - $num2;
$num1 = $num1 - $num2;
echo "After Swapping \n First Number = $num1 \n Second Number = $num2";
?>
                                      

OUTPUT

Enter the first number: 55
Enter the second number: 67
Before Swapping
 First Number = 55
 Second Number = 67
After Swapping
 First Number = 67
 Second Number = 55