PHP Program to program to swap two variables


February 15, 2024, Learn eTutorial
1662

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 in 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. After that, we have to create a temporary variable and assign the value of the first number variable into the temporary variable and assign the value of the second number variable into the first number variable and at last assign the value of the temporary variable into the second number variable. And for showing the result after the swapping we can print the variables.

ALGORITHM

Step 1: Accept the first number from the user into the variable num1

Step 2: Accept the second number from the user into the variable num2

Step 3: After reading the values into the variables now we have to create a temporary variable temp and assign the value of variable num1 into it.

Step 4: After assigning the value of variable num1 into temp we have to assign the value of variable num2 into the variable num1

Step 5: After that, we have to assign the value of the variable temp into the variable num2

Step 6: By the completion of the above step we have completed the swapping now we can print the values of variable num1 and num2 as swapped.

PHP Source Code

                                          <?php
$num1 = readline("Enter the first number: ");
$num2 = readline("Enter the second number: ");
$temp = $num1;
$num1 = $num2;
$num2 = $temp;
echo "\n After swapping:\n";
echo " Fist Number = $num1 \n Second Number = $num2";
?>
                                      

OUTPUT

Enter the first number: 69
Enter the second number: 54

After swapping:
Fist Number = 54
Second Number = 69