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.
3 replies on “Answer To Peter Bowyer’s Question”
Thanks for the code Joseph, these look to be good answers to the problem – I’ll go and see which looks neater in FormProcessor now 🙂
Sorry you had problems posting to my blog – the username/password are in the ‘message’ displayed in the HTTP Basic Authentication dialogue. I implemented spam protection this way and haven’t had any spam since doing it.
..Although for some reason in the FormProcessor code the first construct didn’t work (it was the more suitable one of the two). It messed up handling tags that should have been caught by the ‘default’ statement. Most odd, as a demo similar to your one was working fine!
Hmmmm.
I only did basic testing to see the two solutions would work in PHP (4.3.8). It wouldn’t surprise me if they both needed some tweaking to get exactly the results you want.