PHP Variable Switching - How not to do it!
Posted on January 5th, 2008 in PHP |
Over on TalkPHP, there is a wee contest running with the essential idea being to swap around the values belonging to two variables in 8 lines or less. There are very simple, very obvious ways of doing this which you would normally use (I don't think I've ever actually had to swap the values of two variables in real coding!) but for fun, the entire point of the contest is to be creative with the solutions.
We are presented with
$a = 1; $b = 2;
and quite simply, the aim is to end up with $a having a value of 2 and $b having a value of 1. Easy!
Here are a few cool little approaches from other members on TalkPHP:
Wildhoney
list($a, $b) = str_split(strrev($a . $b), 1);
A couple from Alan @ CIT
$a ^= $b ^= $a ^= $b;
$db = sqlite_open('talkphp.db'); sqlite_query($db, 'CREATE TABLE talkphp (var varchar(2), val int)'); sqlite_query($db, "INSERT INTO talkphp (var, val) VALUES ('a', ". $a . ")"); sqlite_query($db, "INSERT INTO talkphp (var, val) VALUES ('b', ". $b . ")"); $vars_r = sqlite_query($db, 'select * from talkphp'); $vars_a = sqlite_fetch_all($vars_r); $a = $vars_a[1]['val']; $b = $vars_a[0]['val'];
And here is mine, which came with the following disclaimer:
Disclaimer: I hold no responsibility for any physical or mental injury to yourself or those in your immediate vicinity caused as a direct result of looking at my method of swapping the variables' values. You have been warned.
$a = 1; $b = 2; /* 1 */ $szStory = 'The quick brown fox jumps over the lazy dog. How awesome is that?'; /* 2 */ $aMess = compact(array_unique(str_split(preg_replace('/[^a-z]+/', '', strtolower($szStory))))); /* 3 */ foreach (array_reverse(array_keys($aMess)) as $iKey => $szVar) /* 4 */ (isset($pMess) or $pMess = new stdClass) and $aTemp = array_values($aMess) and $pMess->$szVar = $aTemp[$iKey]; /* 5 */ for($iPos = 0, $iLen = count($aPos = array(2, 17, -2, 8, 32, 2, -6)); $iPos < $iLen; $iPos++) /* 6 */ (isset($szFunc) or $szFunc = '' or 0123 === 0x53) and $szFunc .= strtolower($szStory[$iPos + $aPos[$iPos]]); /* 7 */ $szFunc(get_object_vars($pMess)); /* 8 */ unset($szStory, $aMess, $iKey, $szVar, $pMess, $aTemp, $iPos, $iLen, $aPos, $szFunc); // Now, magically, $a = 2 and $b = 1... don't ask how. header('Content-Type: text/plain; charset=utf-8'); var_dump($a, $b);
I look forward to seeing what other people come up with! My submission has already seemingly caused some unpleasant side-effects by those trying to decipher it. Alan @ CIT said, "[ I ] followed the code about halfway through then I'm fairly certain I blacked out" and danielneri responded with, "That hurts to read. A lot! I'm not even going to attempt to read that haha". I did warn them.

