TalkPHP
 
 
Account Login
Latest Articles
» The basic usage of PHPTAL, a XML/XHTML template library for PHP
» Vulnerable methods and the areas they are commonly trusted in.
» Simple way to protect a form from bot
» The Basics On: How Session Stealing Works
» How to keep your forms from double posting data
Advertisement
Associates
Associates
techtuts Darkmindz
CSS Tutorials Tutorialsphere.com - Free Online Tutorials
Boston PHP SurfnLearn
Reply
 
LinkBack Thread Tools Search this Thread Display Modes
Old 01-04-2008, 04:13 PM   #1 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,587
Thanks: 72
Wildhoney is on a distinguished road
Big Grin The most inventive way to switch 2 values

OK! A little game for you all

The only objective is to switch the values of $a and $b. The values of $a and $b are 1 and 2, respectively:

php Code:
$a = 1;
$b = 2;

So for example this is an easy way to do it:

php Code:
$c = $a;
$a = $b;
$b = $c;

However! We're not looking for the simplest way to do it, or the fastest, but rather, the most inventive way to do it! There are a couple of rules and those are:
  1. eval and create_function functions are disallowed.
  2. 8 lines maximum but lines with only { and } on do not count towards that total. This does not include the 2 initial assignments of $a and $b, or any echoes of the values $a or $b.
  3. You must have only one semi-colon per line (;) unless of course it's used elsewhere apart from indicating the end of a line. Thus you're not allowed to fuse 2 lines together into 1. The exception is a for loop to where you're allowed 2.

So basically $a must equal 2 and $b must equal 1 at the end of your code.

I'll start us off:

php Code:
list($a, $b) = str_split(strrev($a . $b), 1);

var_dump($a);
var_dump($b);

Put that mind to work! Oh, and just for Karl, you can't just set $a to 2 and $b to 1 You have to reference the first 2 variables set!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is online now  
Reply With Quote
The Following User Says Thank You to Wildhoney For This Useful Post:
codefreek (01-05-2008)
Old 01-04-2008, 06:50 PM   #2 (permalink)
The Acquainted
 
sjaq's Avatar
 
Join Date: Nov 2007
Location: Netherlands
Posts: 104
Thanks: 9
sjaq is on a distinguished road
Default

PHP Code:
<?php 

    $a 
1;
    
$b 2;
    
    
// just the simplest way...
    
list($a$b) = array($b$a);
    
    
var_dump($a);
    
var_dump($b);

    
$c 1;
    
$d 2;
    
    list(
$c$d) = array_reverse(array($c$d));
    
    
var_dump($c);
    
var_dump($d);

    
$e 1;
    
$f 2;
    
    
$vars = array('e' => $e'f' => $f);
    
extract(array_combine(array_reverse(array_keys($vars)), array_values($vars)));
    
    
var_dump($e);
    
var_dump($f);

?>
Not that innovative but wanted to give it a try..
sjaq is offline  
Reply With Quote
Old 01-04-2008, 07:12 PM   #3 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,587
Thanks: 72
Wildhoney is on a distinguished road
Default

Lol at the last one Very confusing!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is online now  
Reply With Quote
Old 01-04-2008, 09:03 PM   #4 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 482
Thanks: 51
Alan @ CIT is on a distinguished road
Default

ok, turns out I should have fully read the first post before I started on this - I completely missed the 8-lines rule until now

As such, the code below isn't my entry - I'll be off to make an 8-line entry now - but since I wrote it, might as well post it :D

I decided to use the Google Spreadsheet service to swap the values over (using the Zend Framework GData library)

This code requires you have a valid google account, a spreadsheet created with the same name as $spreadsheet in the code and the Zend Framework installed in /library.

PHP Code:
<?php

// The challange!
$a 1;
$b 2;

// Google Account details, spreadsheet name and worksheet name
$user 'yourAccount@gmail.com';
$pass 'secret';

$spreadsheet 'talkphp_example';
$worksheet 'Sheet1';

// Load the Zend bits
set_include_path('.' PATH_SEPARATOR './library' PATH_SEPARATOR get_include_path());

require_once 
'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Http_Client');
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Spreadsheets');

// Connect to Google
$authService Zend_Gdata_Spreadsheets::AUTH_SERVICE_NAME;
$httpClient Zend_Gdata_ClientLogin::getHttpClient($user$pass$authService);
$gdClient = new Zend_Gdata_Spreadsheets($httpClient);

// Fetch and set the spreadsheet
$feed $gdClient->getSpreadsheetFeed();

foreach(
$feed->entries as $entry)
{
    if (
$entry->title->text == $spreadsheet)
    {
        
$key split ('/'$entry->id->text);
        
$spreadsheetId $key[5];
    }
}

// Find and set the worksheet
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($spreadsheetId);
$feed $gdClient->getWorksheetFeed($query);

foreach(
$feed->entries as $entry)
{
    if (
$entry->title->text == $worksheet)
    {
        
$key split ('/'$entry->id->text);
        
$worksheetId $key[8];
    }
}

// Set A1 to $a and A2 to $b
$gdClient->updateCell(1,1$a$spreadsheetId$worksheetId);
$gdClient->updateCell(1,2$b$spreadsheetId$worksheetId);

// Fetch the cells
$query = new Zend_Gdata_Spreadsheets_CellQuery();
$query->setSpreadsheetKey($spreadsheetId);
$query->setWorksheetId($worksheetId);
$cellFeed $gdClient->getCellFeed($query);

// Switch the values over!
foreach($cellFeed as $cellEntry)
{
    if (
$cellEntry->cell->getRow() == '1' && $cellEntry->cell->getColumn() == '1')
    {
        
// A1
        
$b $cellEntry->cell->getText();
    }

    if (
$cellEntry->cell->getRow() == '1' && $cellEntry->cell->getColumn() == '2')
    {
        
// A2
        
$a $cellEntry->cell->getText();
    }
}

// $a should now be '2' and $b should now be '1'
echo '$a: ' $a '<br />';
echo 
'$b: ' $b '<br />';
Dam 8 line rule! brb with a new entry :D

Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
The Following User Says Thank You to Alan @ CIT For This Useful Post:
codefreek (01-05-2008)
Old 01-04-2008, 09:17 PM   #5 (permalink)
La Vida es Sueño
Advanced Programmer Top Contributor 
 
Wildhoney's Avatar
 
Join Date: Sep 2007
Location: Oldham
Posts: 1,587
Thanks: 72
Wildhoney is on a distinguished road
Default

Lol! Man, you're crazy ! That's why I made the 8 line rule. To stop people wasting so much time on something like this.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
Send a message via AIM to Wildhoney Send a message via MSN to Wildhoney Send a message via Yahoo to Wildhoney
Wildhoney is online now  
Reply With Quote
The Following User Says Thank You to Wildhoney For This Useful Post:
codefreek (01-05-2008)
Old 01-04-2008, 09:18 PM   #6 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 482
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Ok, my new attempt - using bitwise operators to swap the values about:

PHP Code:
<?php

$a 
1;
$b 2;

$a ^= $b ^= $a ^= $b;

echo 
$a;
echo 
$b;
Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
The Following User Says Thank You to Alan @ CIT For This Useful Post:
codefreek (01-05-2008)
Old 01-04-2008, 09:18 PM   #7 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 482
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Quote:
Originally Posted by Wildhoney View Post
Lol! Man, you're crazy ! That's why I made the 8 line rule. To stop people wasting so much time on something like this.
It's ok, I got plenty of time to waste :D

Alan
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
Old 01-04-2008, 09:29 PM   #8 (permalink)
Moderateur
RegEx Guru PHP Guru Top Contributor Advanced Programmer 
 
Salathe's Avatar
 
Join Date: Apr 2007
Posts: 714
Thanks: 2
Salathe is on a distinguished road
Default

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.

PHP Code:
$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(217, -28322, -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); 
__________________
Salathe is offline  
Reply With Quote
The Following User Says Thank You to Salathe For This Useful Post:
codefreek (01-05-2008)
Old 01-04-2008, 09:41 PM   #9 (permalink)
The Addict
 
Join Date: Nov 2007
Posts: 265
Thanks: 2
TlcAndres is on a distinguished road
Default

I made this...then read the rules, I broke the majority of the rules

PHP Code:

<?
    $a 
1;
    
$b 2;    
    
preg_match_all('/[1-9]/',serialize(array($a,$b)),$ar);
    
$ar reset($ar);
    foreach(
array_keys($ar) as $k)
    {
        
$r next($ar);
        if(empty(
$ar[$k]) or $ar[$k] == $r)
        {
            unset(
$ar[$k]);
        }
        else
        {
            
$a $ar[$k];
            
$a = ($a) + (40 10 .5 5.5 << 5.5 >> 10);
            
$ar[$k] = $a;
        }
    }
    
$r array_reverse(array_splice($ar,1));
    
$let 'a';
    while(list(,
$v) = each($r))
    {
        
$string .= chr(36) . $let chr(61) . $v chr(59);
        ++
$let;
    }
    
ob_start();
    eval(
$string);
    
ob_get_clean();
    
var_dump($a);
    
var_dump($b);
?>
It was still fun though

(I know, nearly everything there is useless)
TlcAndres is offline  
Reply With Quote
The Following User Says Thank You to TlcAndres For This Useful Post:
codefreek (01-05-2008)
Old 01-04-2008, 09:41 PM   #10 (permalink)
Alan @ CIT
Member of the Month
The Frequenter
Member of the Month Top Contributor 
 
Alan @ CIT's Avatar
 
Join Date: Apr 2005
Location: South UK
Posts: 482
Thanks: 51
Alan @ CIT is on a distinguished road
Default

Wow, that's insane Salathe :D Followed the code about halfway through then I'm fairly certain I blacked out :D

Another way to do it (if in doubt, use a database!):

PHP Code:
<?php

$a 
1;
$b 2;

$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'];

echo 
$a;
echo 
$b;
Alan.
Send a message via MSN to Alan @ CIT
Alan @ CIT is offline  
Reply With Quote
The Following User Says Thank You to Alan @ CIT For This Useful Post:
codefreek (01-05-2008)
Old 01-04-2008, 09:47 PM   #11 (permalink)
The Addict
 
Join Date: Nov 2007
Posts: 265
Thanks: 2
TlcAndres is on a distinguished road
Default

I'm fairly certain this thread will be counter-productive to all those who have started to learn PHP


fun non the less though
TlcAndres is offline  
Reply With Quote