Categories
PHP Programming

Answer To Peter Bowyer’s Question

Peter Bowyer asked a question on his blog about optional case statements in PHP. After a couple of minutes I came up with two possible solutions. I tried to post the solutions as a comment to the blog entry, but it kept asking for a login in order to post a comment. I don’t have an account at his blog and I couldn’t find any info on how to create one. So I’m using this post to show a solution to his question. Hopefully the TrackBack to his entry works so he’ll be able to find this. Follow the link above to read the original question, below are the two possible solutions I came up with:

Solution 1)

$foo = 'baz';
switch($foo){
        case 'bar':
            print 'BAA';
            break;
        case 'moo' && !empty($varisset):
            print 'ANIMAL!';
            break;
        case 'brrrrr' && !empty($varisset):
            print 'COLD?';
            break;
} // switch

Solution 2)

$foo = 'moo';
switch($foo){
        case 'bar':
            print 'BAA';
            break;
        case (!empty($varisset)):
            switch($foo) {
                case 'moo':
                    print 'ANIMAL!';
                    break;
                case 'brrrrr':
                    print 'COLD?';
                    break;
            } //switch
            break;
} // switch

I’ve only done some basic testing to see if these work. I haven’t done any sort of benchmarking to see if one is faster than the other. I’d guess that solution 2 would be faster, but I don’t have any data to back that up.