php-general | 2003022
Date: 02/21/03
- Next message: Tom Rogers: "Re: [PHP] Logging Referer"
- Previous message: Ray Hunter: "[PHP] Utah PHP User"
- In reply to: Chris: "[PHP] Array instead of Switch"
- Next in thread: David Otton: "Re: [PHP] Array instead of Switch"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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 <email protected> * society and not sufficient moral courage. (work) davidtgwork <email protected> -- Mary Baker Eddy, "Science and Health" http://justpickone.org/davidtg/ Shpx gur Pbzzhavpngvbaf Qrprapl Npg!
- application/pgp-signature attachment: stored
- Next message: Tom Rogers: "Re: [PHP] Logging Referer"
- Previous message: Ray Hunter: "[PHP] Utah PHP User"
- In reply to: Chris: "[PHP] Array instead of Switch"
- Next in thread: David Otton: "Re: [PHP] Array instead of Switch"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]

