Write a php program to swap two numbers using temporary variable

Write a php program to swap two numbers using temporary variables. This program will swap the two numbers in PHP scripting language. This program will print the result after interchanging the values in output¬† screen in php language. The act of swapping two variables in computer programming refers to the exchange of the variables’ values. This is usually done with data stored in memory. Swaps are used to shift the placements of data in comparison sorts. Swap is a built-in function in several computer languages.

<?php 
$a = 5;
$b = 10;
$temp = $a;
$a = $b;
$b = $temp;
echo "after swapping";
echo "a =".$a." b=".$b;
?>

 

Output:

after a=10 b=5

What is swapping and how does it works in php

In memory, to replace pages or chunks of data. Swapping is a mechanism that allows a computer to run programs and modify data files that are larger than the primary memory. The operating system copies as much data into main memory as feasible and saves the rest to disc. Swapping two integers entails swapping the values of two variables. For example, if variable num1 has 20 and variable num2 has 40, the swapped values are num1 has 40 and num2 has 20.

What is temporary variable and why it is needed

Temp is a shorthand for “temporary variable,” which allows you to save and reuse an expression’s value. It’s utilised for swapping and to improve the program‘s readability. This is essentially a catch-all term for items that are made and then soon discarded, having an extremely short lifespan. The principle is applicable to a wide range of languages. In most languages, the principles for determining how long a variable exists are similar.

Temporary variables are commonly labelled using abbreviations of the term temporary, such as temp, tmp, or simply t, or with common metasyntactic variable names, the most prevalent of which being foo, bar, and baz.