Home >>PHP Tutorial >How to swap two numbers in PHP

How to swap two numbers in PHP

How to swap two numbers in PHP

<?php 
extract($_POST);
if(isset($swap))
{
	//first number
	$x=$fn;
	//second number
	$y=$sn;
	
	//third is blank
	$z=0;
	
	//now put x's values in $z
	$z=$x;
	
	//and Y's values into $x
	$x=$y;
	
	//again store $z in $y
	$y=$z;
	
	
	//Print the reversed Values
	echo "<p align='center'>Now First numebr is : ". $x ."<br/>";
	echo "and Second number is : ". $y."</p>";
}
?>

<form method="post">
<table align="center">
	<tr>
		<td>Enter First number</td>
		<td><input type="text" name="fn"/></td>
	</tr>
	<tr>
		<td>Enter Second number</td>
		<td><input type="text" name="sn"/></td>
	</tr>
	<tr>
		<td colspan="2" align="center">
		<input type="submit" value="Swap Numbers" name="swap"/></td>
	</tr>
</table>
</form>

Swap two variables value without using third variable in php

<?php 
//swap two numbers without using third variable
$x=20;
$y=10;

//add x and y, store in x i.e : 30
$x=$x+$y;

//subtract  10 from 30  i.e : 20 and store in y
$y=$x-$y; 

//subtract 20 from 30 i.e : 10 and store in x
$x=$x-$y;

//now print the reversed values
echo "Now x contains : ". $x ."<br/>";
echo "and y contains : ". $y;

?>

Without Using Third Variable but using Some Predefined Functions

<?php 

$a = 10;

$b = 20;

list($a, $b) = array($b, $a);

echo  $a . " " . $b;

?>

No Sidebar ads