[Solved] How to swap 2 variables (their values) in PHP?

  

5
Topic starter

I have 2 variables. I want to swap them. Meaning swapping their vaules...

How can I do it in PHP?

For example:

$variable1 = "something1";
 
$variable2 = "something2";

I want:

$variable1 = "something2";
 
$variable2 = "something1";

Thanks

1 Answer
4

Imagine you have 2 buckets full with water.

In the 1st bucket there is pink water; In the 2nd one there is blue water.

How can you swap the water - so in the 1st one there is blue water and in the 2nd one there is pink water?

Easy! You will need an empty 3rd bucket;

First you will need to pour the pink water from the 1st bucket into the 3rd one (initially empty).

Secondly you will need to pour the blue water from the 2nd bucket into the 1st one (now currently empty).

And lastly you will need to pour the pink water from the 3rd bucket into the 2nd one.

Here is a picture:

swap 2 variables in php

...in PHP is the same with the above mentioned example!

Here is the code (again with buckets :-):

<?php
 
$bucket1 = "pink water";
$bucket2 = "blue water";
 
//ORIGINAL variables (buckets):
echo "ORIGINAL:" . PHP_EOL;
echo 'In $bucket1: ' . $bucket1 . PHP_EOL;
echo 'In $bucket2: ' . $bucket2 . PHP_EOL;
 
//LOGIC WITH THE 3RD BUCKET:
$bucket3 = "";//the 3rd bucket is initially empty
$bucket3 = $bucket1;//pink water from $bucket1 into empty $bucket3
$bucket1 = $bucket2;//blue water from $bucket2 into empty $bucket1
$bucket2 = $bucket3;//pink water from $bucket3 into empty £bucket2
echo PHP_EOL;
 
//SWAPPED variables (buckets):
echo "SWAPPED:" . PHP_EOL;
echo 'In $bucket1: ' . $bucket1 . PHP_EOL;
echo 'In $bucket2: ' . $bucket2 . PHP_EOL;

and this is the output:

value swapping of two variables in php

Share: