Quantcast
Channel: Lil Josh » PHP
Viewing all articles
Browse latest Browse all 11

Swapping variables in PHP

$
0
0

I’ve created a short and sweet PHP function swap() to exchange/swap the values of two PHP variables. Here it is in action:

<?php

$cat = "cat";
$dog = "dog";

swap($cat,$dog);

echo "$cat goes meow and $dog goes woof"; //dog goes meow and cat goes woof

function swap(&$var1, &$var2) {
    $tmp = $var1;
    $var1 = $var2;
    $var2 = $tmp;
}

?>

If you’re running this function a lot (e.g. millions of iterations) it’s actually faster to just perform the swap without the function. For example:

for($i = 0; $i < 10000000; $i++) {
    $tmp = $var1;
    $var1 = $var2;
    $var2 = $tmp;
}

Thanks @dnaslave for providing efficiency feedback! :]


Viewing all articles
Browse latest Browse all 11

Trending Articles