How to swap two numbers in PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | <?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?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
1 2 3 4 5 6 7 8 9 10 11 | <?php $a = 10; $b = 20; list($a, $b) = array($b, $a); echo $a . " " . $b; ?> |