The Most Active and Friendliest
Affiliate Marketing Community Online!

“AdsEmpire”/  Direct Affiliate

Tip : Swap values of two variables without using a third variable

D

dman_2007

Guest
Here's a handy trick for you to swap values of two variables without using another variable :

Code:
  list($a, $b) = array($b, $a);

The statement above will transfer value of variable $a to variable $b and vice versa.
 
Here is one other method by which the values can be swaped in all the programing languages:
Define 2 variable depending upon the syntax of the language:
a=20
b=30

Now compare both the variable if b>a then
a = b - a ==> 30 - 20 = 10
b = b - a ==> 30 - 10 = 20
a = a + b ==> 10 + 20 = 30


Else vice varsa.

This will also do the work.
 
Another good method, a bit more involved but gets the job done. Here's another method using ^ (XOR) operator :

Code:
<?php
  $a = 10;
  $b = 20;
  
  echo '$a => ' , $a, ' $b => ', $b, '<br />';
  
  $a = $a ^ $b;
  $b = $a ^ $b;
  $a = $a ^ $b;
  
  echo '$a => ' , $a, ' $b => ', $b, '<br />';
?>
 
MI
Back