How we can Swap two numbers in PHP

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>
<html>
<head><title>Swap two numbers in PHP</title>
</head>
<body>
<!--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" />
</form>
<!--end of form-->

<!--php code starts-->
<?php

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

$num1=$_POST['num1'];
 $num2=$_POST['num2'];
 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-->

</body>
</html>

OUTPUT:

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

 

Leave a Comment