BlogKontaktTagcloud

Array instead of switch-case in php

First of all, be warned, this article has no pratical relevance. It even might guide you to bad code. But this week it just popped into my mind that I could use an array instead of a switch-case construct. So see how we can do this. This is the example for the switch in the php manual.

switch ($i) {
case 
0:
    echo 
"i equals 0";
    break;
case 
1:
    echo 
"i equals 1";
    break;
case 
2:
    echo 
"i equals 2";
    break;
}
Now I'm able to implement this in a array, for that I put the code for every case statement in a arrayfield Afterwards I can access the field over the parameter and execute the code in it with eval.Here's the example: (Take care to not forget the semicolon in the code string)

$case[0] = "echo \"i equals 0\";";
$case[1] = "echo \"i equals 1\";";
$case[2] = "echo \"i equals 2\";";
eval($case[$i]);
Looks pretty, but what to do if you have to do the default statment. Nothing easier then that, we just have to look if eval goes ok and if not we do something after AND-short circuit:
eval($case[$i]) === false && print("default");
Ähnliche Beiträge:
What's php like?
Zend Framwork 1.5 is out
Coding Contest addicted
Coding Contest
A eventfull PHP-Week
Comments (3)  Permalink

comments

chregu @ 11.01.2008 16:11 CEST
I hope your new framework doesn't contain such "creative" programming :)
leo @ 15.01.2008 10:35 CEST
Didn't found a businesscase for this code until now ;-)
Silvan @ 15.01.2008 13:45 CEST
You could offer classes in "How to program without control flow statements just by using eval(), || and &&" :-)

add a comment

The Trackback URL to this comment is:
http://leo.freeflux.net/blog/plugin=trackback(2538).xml

This blog is gravatar enabled.
Your email adress will never be published.
Comment spam will be deleted!

Name*
E-Mail
For Spammers Only
URL
Kommentar*
E-Mail Benachrichtigung bei neuen Kommentaren zu diesem Eintrag
Speichere meine Daten (braucht Cookies)