...

View Full Version : Switch List vars in Foreach



zro@rtv
03-12-2007, 12:06 AM
I just know I'm being stupid here, but I can;t seem to kick my brain into thinking of wtf is wrong with my logic.

functionality im trying to achieve:

<?php

function do_something($opt, $file){

$lines = gzfile($file);
foreach ($lines as $line){
switch ($opt){
case 1:
list($foo, $bar) = explode(',', $line);
break;
case 2:
list($foo, $bar, $baz) = explode(',', $line);
break;
case 3:
list($foo, $bar, $baz, $boom) = explode(',', $line);
break;
}
}
}

?>

This seems ridiculous to sets the case on every line.
rather it would make sense to test case before the foreach and then pass the vars to list? But I can't think of how to do this for some reason?

I can't wait to see the obvious answer to this and kick myself hard.

zro@rtv
03-12-2007, 01:32 AM
ok, so I think I worded that poorly.
obviously I believe this is better than what I had posted:



<?php

function do_something($opt, $file){

$lines = gzfile($file);

switch ($type){
case 1:
foreach ($lines as $line){
list($foo, $bar) = explode(',', $line);
}
break;
case 2:
foreach ($lines as $line){
list($foo, $bar, $baz) = explode(',', $line);
}
break;
case 3:
foreach ($lines as $line){
list($foo, $bar, $baz, $boom) = explode(',', $line);
}
break;
}
}
}
?>


But that seems redundant.
Wha tI'm looking for is a more elegant construct something that perhaps lokos more like this.




<?php

function do_something($opt, $file){

switch ($opt){
case 1:
AUTO-MAGICAL
break;
case 2:
AUTO-MAGICAL
break;
case 3:
AUTOMAGICAL
break;
}

$lines = gzfile($file);
foreach ($lines as $line){
list(AUTO-MAGICAL) = explode(',', $line);
}
}

?>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum