Re: Array instead of Switch

From: Date: Sat, 22 Feb 2003 04:04:50 +0000
Subject: Re: Array instead of Switch
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-136593@lists.php.net to get a copy of this message
Chris, et al -- ..and then Chris said... % % Let's say I need to take one of 20 actions depending on a form selection. I % could use a switch statement with 20 cases, but I could also do something % like: % % // Pretend this comes from a form % $formchoice = "mars"; % % % $response = array( % "mars" => "go_mars()", % "mercury" => "go_mercury()", % "earth" => "go_earth()"); % % foreach ($response as $choice => $action) % { % if (strtoupper($formchoice) == strtoupper($choice)) % { % eval("$action;"); % } % } % % But are there even better ways? I'm just pulling this out of my ear, but assuming the structure you gave what about a simple eval("$response[$formchoice];") ; to match if it matches and do nothing if it doesn't? In fact, I got curious, so here is some test code I just whipped up; note that when the choice is 'comet' nothing happens. function go_mars() { print "Welcome to mars, dude!\n" ; } $formchoice = "comet" ; $response = array ( "mars" => "go_mars()" , "mercury" => "go_mercury()" , // continue ad nauseam ) ; print "Will we eval?\n" ; eval ("$response[$formchoice];") ; print "DONE!\n" ; Seems like this ought to be pretty safe since you're writing the go_* functions and otherwise nothing matches and you eval a "". HTH & HAND :-D -- David T-G * There is too much animal courage in (play) davidtg@justpickone.org * society and not sufficient moral courage. (work) davidtgwork@justpickone.org -- Mary Baker Eddy, "Science and Health" http://justpickone.org/davidtg/ Shpx gur Pbzzhavpngvbaf Qrprapl Npg!

« previous php.general (#136593) next »