your image

PHP Swapping Two Numbers Program - javatpoint

javapoint
Related Topic
:- PHP Java information technology

Swapping two numbers

Two numbers can be swapped or interchanged. It means first number will become second and second number will become first.

For example

  1. a = 20, b = 30  
  2. After swapping,  
  3. a = 30, b = 20  

There are two methods for swapping:

  • By using third variable.
  • Without using third variable.

Swapping Using Third Variable

Swap two numbers 45 and 78 using a third variable.

 

2. Objects in PHP | Build a CMS using OOP PHP tutorial MVC [2020]

Example:

  1. <?php  
  2. $a = 45;  
  3. $b = 78;  
  4. // Swapping Logic  
  5. $third = $a;  
  6. $a = $b;  
  7. $b = $third;  
  8. echo "After swapping:<br><br>";  
  9. echo "a =".$a."  b=".$b;  
  10. ?>  

Output:

Swapping Without using Third Variable

Swap two numbers without using a third variable is done in two ways:

  • Using arithmetic operation + and ?
  • Using arithmetic operation * and /

Example for (+ and -):

  1. <?php  
  2. $a=234;  
  3. $b=345;  
  4. //using arithmetic operation  
  5. $a=$a+$b;  
  6. $b=$a-$b;  
  7. $a=$a-$b;  
  8. echo "Value of a: $a</br>";  
  9. echo "Value of b: $b</br>";  
  10. ?>  

Output:

Example for (* and /):

  1. <?php  
  2. $a=234;  
  3. $b=345;  
  4. // using arithmetic operation  
  5. $a=$a*$b;  
  6. $b=$a/$b;  
  7. $a=$a/$b;  
  8. echo "Value of a: $a</br>";  
  9. echo "Value of b: $b</br>";  
  10. ?>  

Output:

Comments