Swapping Two Numbers in PHP

Swapping two numbers involves exchanging their values. There are two common methods for swapping: using a third variable and without using a third variable.

Example:

x = 5, y = 4
After swapping,
x = 4, y = 5 

In PHP, we can swap using two methods:

  • By using the 3rd variable,
  • without using a third variable.

PHP Example:

Method 1: Using a Third Variable

<?php
$x = 14;
$y = 19;

// Before swapping
echo "Before <br>";
echo "x = " . $x . "<br>";
echo "y = " . $y . "<br>";

// Swapping using a third variable
$thirdVar = $x;
$x = $y;
$y = $thirdVar;

// After swapping
echo "After swapping:<br>";
echo "x = " . $x . "  y = " . $y;
?>

Output:

Before:
x = 14
y = 19

After swapping:
x = 19 y = 14

Method 2: Without Using a Third Variable

<?php  
$x = 156;  
$y = 932;

// Before swapping
echo "Before swapping:<br>";
echo "x = $x <br>";
echo "y = $y <br>";

// Swapping without using a third variable
$x = $x + $y;  
$y = $x - $y;  
$x = $x - $y;  

// After swapping
echo "After swapping:<br>";
echo "x = $x <br>";
echo "y = $y <br>";
?>  

Output:

Before swapping:
x = 156
y = 932

After swapping:
x = 932
y = 156

Explanation:

  1. Method 1: Using a Third Variable:
    • Before swapping, the values of x and y are displayed.
    • Swapping is performed using a third variable, and the updated values are shown.
  2. Method 2: Without Using a Third Variable:
    • Before swapping, the values of x and y are displayed.
    • Swapping is performed without using a third variable, and the updated values are shown.