Created
October 6, 2011 18:12
-
-
Save JeffreyWay/1268154 to your computer and use it in GitHub Desktop.
Lookups instead of Switch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
# Instead of | |
$name = 'Jeff'; | |
switch ($name) { | |
case 'Jeff': | |
echo "I'm Jeff"; | |
break; | |
case 'Joe': | |
echo "I'm Joe"; | |
break; | |
case 'John': | |
echo "I'm John"; | |
break; | |
} | |
# Do | |
$lookup = array( | |
"Jeff" => "I'm Jeff", | |
"Joe" => "I'm Joe", | |
"John" => "I'm John", | |
"default" => "I'm Error" | |
); | |
echo $lookup[$name]; | |
# Or if you need a default | |
echo isset($lookup[$name]) ? $lookup[$name] : $lookup['default']; |
@willsteinmetz You'll get a Notice not an error.
Yeah, sorry -- notice, not error. Just do a quick test to see if the key exists.
I do this when creating custom form errors. Setup an errors array and then use the cleansed $_POST key submitted as the lookup. Works great.
Handy solution with simple return values. In case of more complex actions, I usually use callback functions.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Anyone catch the Zelda 2 reference? :)