swap two variables | swap two variables in php

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

For example

Originally
a = 20, b = 25
After swapped it will become
a = 25, b = 20 

Swapping can be done by 2 ways.

  • Using third (temporary) variable
  • without using third (temporary) variable

Using Third Variable

<?php

$a = 20;
$b = 25;

echo "Without exchange a = $a and b = $b";

$temp = $a;
$a = $b;
$b = $temp;

echo "<br/> After exchange <b> a = $a </b> and <b> b = $b </b>";
?>
swapped 2 variables
swapped 2 variables

swap 2 variables without using third variable.

<?php
$a = 20;
$b = 25;

echo "Without exchange a = $a and b = $b";
$a = $a + $b; // 20 + 25 = 45
$b = $a - $b; // 45 - 25 = 20 
$a = $a - $b; // 45 - 20 = 25

echo "<br/> <br/> After exchange <b> a = $a </b> and <b> b = $b </b>";

?>
swapped without using 3rd variable
swapped without using 3rd variable

Note: br or b used for break line and bold.

Swapped 2 variables

Pradip Mehta

I am a well-organized professional in Drupal Development and PHP web development with strong script handling knowledge or automation process with PHP. I have advanced computer skills and am a proficient multitasker.