@pcthugFeb 07.2007 — #Try a switch statement with a [I]default[/I] case to catch bad requests[code=php] switch (@(int)$_GET['id']) { case 1 : $url = 'http://www.google.com/'; break; case 2 : $url = 'http://www.yahoo.com/'; break; case 3 : $url = 'http://www.amazon.com/'; break;
// the default URL to redirect to (will be called if id does not match any of the previous cases) default: $url = 'http://www.webdeveloper.com/'; }
@NightShift58Feb 07.2007 — #You should consider using IF/ELSEIF/ELSE instead, as it is both more efficient and less error-prone:[code=php]<?php $userCHOICE = intval($_GET['id']);
IF {$userCHOICE == 1) : $url = 'http://www.google.com/'; ELSEIF {$userCHOICE == 2) : $url = 'http://www.yahoo.com/'; ELSEIF {$userCHOICE == 3) : $url = 'http://www.amazon.com/'; ELSE : // the default URL to redirect to (will be called if id does not match any of the previous tests) $url = 'http://www.webdeveloper.com/'; ENDIF;
header("Location: $url"); ?>[/code]SWITCH/CASE is really a poor alternative to IF/ELSE. In another thread, Bokeh demonstrated how treacherous it can be and unless you have a special reason for using some of its unique control features, you should stay away from it.
@pcthugFeb 07.2007 — #I tried digging up the thread you mentioned NightShift, but to no avail. Anyways, I generally use switch statements whenever I need to compare the same expression two or more times. It offers greater read and maintainability over and if/else statement and is a core feature in all mainstream programming languages.
@NightShift58Feb 07.2007 — #I tried digging up the thread you mentioned NightShift, but to no avail.[/quote]This is a good starting point, though there is some before and after...
It offers greater read and maintainability over and if/else statement[/quote]The "easier" reading is in the eyes of the beholder so I will not disagree. In fact, if it wasn't such a limited and inefficient control structure, I like the simplicity of the statement and the visual aspect - if only it woul live up to the promise...
... and is a core feature in all mainstream programming languages.[/QUOTE]Yes, it is. But so is IF/ELSE.
With the exception that, unlike SWITCH, IF/ELSE is a core feature of machine language and SWITCH requires translation by the compiler so it is broken down to a series of IF/ELSE instructions. Also, not every programming language requires the use of BREAK or similar premature block exit.