Friday, 30 November 2012

SWAP Two Variables in PHP

There are two ways to swap 2 variables in PHP.

<!-- SWAP Values by using Third Variable -->
<?php
$firstInput = 100;
$secondInput = 200;
$swapRefVariable = $secondInput;
$secondInput = $firstInput;
$firstInput = $swapRefVariable;

echo "First Input: ".$firstInput."<br>Second Input: ".$secondInput;
?>
<!-- SWAP Values by using Third Variable -->

<!-- SWAP Values with out using Third Variable - Arithmetic Operation -->
<?php
$firstInput = 100;
$secondInput = 200;
$firstInput = $firstInput + $secondInput;
$secondInput = $firstInput - $secondInput;
$firstInput = $firstInput - $secondInput;

echo "First Input: ".$firstInput."<br>Second Input: ".$secondInput;
?>
<!-- SWAP Values with out using Third Variable Arithmetic Operation -->

No comments:

Post a Comment

Thank you so much for providing your valuable feedback. I will will look into them and update my skills & technologies accordingly.