Skip to content

Instantly share code, notes, and snippets.

@JeffreyWay
Created October 6, 2011 18:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save JeffreyWay/1268154 to your computer and use it in GitHub Desktop.
Save JeffreyWay/1268154 to your computer and use it in GitHub Desktop.
Lookups instead of Switch
<?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'];
@JeffreyWay
Copy link
Author

You'd likely want to set a default as well. :)

@JeffreyWay
Copy link
Author

Haven't tested it, but I'd also imagine that a lookup will be somewhat faster.

@willsteinmetz
Copy link

Maybe I'm confusing PHP with JavaScript, but wouldn't you get an error about an undefined key if you did echo $lookup['Dave'] since the attribute doesn't exist in the array?

@abuisman
Copy link

abuisman commented Oct 6, 2011

Cleaner code, but what about performing more complex tasks than echo-ing?

@JeffreyWay
Copy link
Author

@will - Was just a quick example. You can set a default. Updated the code above to show a quick solution.

@Abulsman - Yeah, it just depends on your needs. This works really well for quick lookup type stuff, where you need to set a value or something.

@mikelbring
Copy link

You probably could use a Closure for more complex tasks.

@JeffreyWay
Copy link
Author

Anyone catch the Zelda 2 reference? :)

@mloberg
Copy link

mloberg commented Oct 6, 2011

@willsteinmetz You'll get a Notice not an error.

@JeffreyWay
Copy link
Author

Yeah, sorry -- notice, not error. Just do a quick test to see if the key exists.

@damonsharp
Copy link

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.

@macodev
Copy link

macodev commented Oct 7, 2011

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