Home » PHP/MySQL, Programming Techniques » Swap Values Without Temp or A Third Variable in PHP


When we need to swap the values of two variables, we use a third variable temporarily to hold the data between swapping.  Something like this:

$tmp = $a;
$a = $b;
$b = $tmp;

Here is another way without using a temp or a third variable.

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

And if you want to make it a function:

function swapValues(&$a, &$b) {
     list($b, $a) = array($a, $b);
$a = 10;
$b = 20;
swapValues($a, $b);
Tags: ,

1 Comment

  1. Rustam.Uz says:

    In that case not creat temp variable, but all the same set(create) array without name.

Leave a Reply

Page optimized by WP Minify WordPress Plugin