PHP Program to Swap Two Numbers

PHP Program to Swap Two Numbers

In programming, there are two different techniques to swap any two numbers in a variable, they are

  • Swap using Temporary Variable
  • Swap without using Temporary Variable

Swap using Temporary Variable

In the following example, we will swap two numbers (25 and 50) using a temporary variable (temp).

Example

PHP Compiler
<?php $num1 = 25; $num2 = 50; $temp = 0; $temp = $num1; $num1 = $num2; $num2 = $temp; echo "After swapping..."; echo "<br> num1 = $num1"; echo "<br> num2 = $num2"; ?>

Swap without using Temporary Variable

In the following example, we will swap two numbers (25 and 50) without using a temporary variable.

Example

PHP Compiler
<?php $num1 = 25; $num2 = 50; $num1 = $num1 - $num2; $num2 = $num1 + $num2; $num1 = $num2 - $num1; echo "After swapping..."; echo "<br> num1 = $num1"; echo "<br> num2 = $num2"; ?>

Join Our Channel

Join our telegram channel to get an instant update on depreciation and new features on HTML, CSS, JavaScript, jQuery, Node.js, PHP and Python.

This channel is primarily useful for Full Stack Web Developer.

Share this Page

Meet the Author