How to Swap Values in PHP

By Shubham G on Dec 12, 2023 254 Views

Example : 1

This PHP script demonstrates a simple way to swap the values of two variables.


- The script first initializes two variables, `$a` and `$b`, with the values 5 and 10, respectively.

- It then prints the values of `$a` and `$b` before the swap.

- To perform the swap, the script introduces a temporary variable `$temp`. It assigns the value of `$a` to `$temp`, then assigns the value of `$b` to `$a`, and finally assigns the value of `$temp` to `$b`. At this point, the values of `$a` and `$b` have been swapped.

- The script then prints the values of `$a` and `$b` after the swap.


This script is a simple demonstration of how to swap two variables in PHP. It's a great exercise for those learning PHP and wanting to improve their understanding of variable assignment. Please note that the output will be different if you change the initial values of `$a` and `$b`.

<?php
$a = 5;
$b = 10;

echo "Before swapping: a = $a, b = $b\n";

// Swap the variables
$temp = $a;
$a = $b;
$b = $temp;

echo "After swapping: a = $a, b = $b\n";
?>

Output : 

Before swapping: a = 5, b = 10

After swapping: a = 10, b = 5

Example : 2

This PHP script demonstrates a way to swap the values of two variables without using a temporary variable. However, it uses a third variable `$c` as a constant.


- The script first initializes three variables, `$a`, `$b`, and `$c`, with the values 10, 20, and 30, respectively.

- It then performs the swap operation in three steps:

    1. `$a` is updated to the sum of `$a`, `$b`, and `$c`.

    2. `$b` is updated to the new value of `$a` minus the original values of `$b` and `$c`. This gives `$b` the original value of `$a`.

    3. `$a` is updated to the new value of `$a` minus the new value of `$b` and the original value of `$c`. This gives `$a` the original value of `$b`.

- Finally, the script prints the new values of `$a` and `$b`.


This script is a demonstration of how to swap two variables in PHP without using a temporary variable, but with the help of a constant. It's a great exercise for those learning PHP and wanting to improve their understanding of variable assignment. Please note that the output will be different if you change the initial values of `$a`, `$b`, and `$c`.

<?php
$a = 10;
$b = 20;
$c = 30;

$a = $a + $b + $c;
$b = $a - $b - $c;
$a = $a - $b - $c;

echo "Value of A is " . $a . '<br/>';
echo "Value of B is " . $b . '<br/>';
?>

Output : 

Value of A is 20

Value of B is 10

Categories : PHP

Tags: #Swap Values , #PHP Basics

  • Related Posts
Loading...