Write a PHP script to swap two numbers. In this tutorial, we are going to write a code to swap two numbers in PHP.
There are multiple approaches by which you can swap two numbers.
i) We can swap two numbers using third or temp variable.
ii) We can swap two numbers without using third variable.
Swap Two Numbers in PHP without using third Variable
Let’s write a PHP script to swap two numbers without using third variable. In this script, we create a method swap which takes two numbers as an argument and print the value of both numbers after swapping.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php /* Initialize the value of a and b. */ $a = 4; $b = 5; function swap ($a, $b){ echo "\n Before swapping the value of a and b is". $a.' '.$b; //Logic to swap two numbers $a = $a + $b; $b = $a - $b; $a = $a - $b; echo "\n After swapping the value of a and b is". $a.' '.$b; } /* Call swap function. */ swap ($a , $b); |
Swap Two Numbers in PHP using Third Variable
We have written a PHP script to swap two numbers without using third variable. Let’s write PHP code which swap two numbers using third variable.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $a = 7; $b = 2; //Function call swapNumbers($a, $b); function swapNumbers($a, $b){ // Swap Logic $temp = $a; $a = $b; $b = $temp; echo "The number after swapping is \n"; echo "Number a =".$a." and b=".$b; } ?> |