Site Loader
Get a Quote

PHP Program to Swap two number…

Swap two numbers Using PHP:

Swap two number:-Hi, readers here we come up with the topic of Swapping Two numbers in PHP. Swapping simply means one number changes to another number.

The logic behind Swapping of Two numbers:

To swap two numbers use the third variable.Assign the first number to the third variable and assign the second number to the first number and then finally assign the second number to the third variable, i.e.

third variable=first number;

first number=second number;

second number=third variable;

Simple Example to Swap two Numbers in PHP:

Here in this example, we used the above logic to program swapping of two numbers in PHP.

First of all, we take two desired value from the user through input field of the form to swap the entered numbers and store it in a variable and then used the third variable to swap these numbers and finally print these numbers after swapping.

Full Source Code:

<!Doctype html>
<head><title>Swap two numbers in PHP</title>
<!--form is created using post method and submiting values itself -->

<form action="" method="post">
Enter first number:
<input type="text" name="num1" /><br>
Enter second number:
<input type="text" name="num2" /><br>
<input type="submit" value="SWAP" />
<!--end of form-->

<!--php code starts-->

// if ($_POST) is true i.e.,checking that the HTML form is submited by the method="post" or not.
/* collecting the value of input field using $_POST['parameter'] 
 and storing it in different variable. */

 echo "Before swapping : the value of first number: $num1 and value of second number: $num2<br><br>";
 //using third variable $tmp to swap two variables.
 $tmp=$num1; //assign num1 to tmp
 $num1=$num2; //assign num2 to num1
 $num2=$tmp; //assign tmp to num2.
 echo "After swapping : the value of first number: $num1 and value of second number: $num2";

<!--php code ends-->



1. Take input from the user:

Swap two numbers

 2. A result of Swap any two numbers:

Swap two numbers

I hope you would like this topic on how to Swap any two numbers in Php using third or temporary variable


Post Author: TechieFlair

Leave a Reply

Your email address will not be published.