PHP tip: Use a regular expression in a switch statement

I came across this nugget while trying to rapidly prototype some new functionality for one of my clients. The client wanted specific artwork to show up for a subset of related items. The prototype has worked out so well, that I haven't yet had to go back add a flag field to the underlying database table. One of the things I had going for me was that the SKUs I needed to identify followed a rigid naming convention. I didn't want to update the switch statement each time a new SKU is added, so instead of this:

switch($sku) {
    case '11012E':
    case '11345E':
    case '11678E':
    case '11901E':
        // ... do stuff
        break;
    case '08012E':
    case '08345E':
        // ... do different stuff
        break;
}

You can use a function in a switch statement to return the result of a regular expression. Even better.

switch($sku) {
    case (preg_match("/^11[0-9]{3}E$/i", $sku) ? $sku : !$sku):
        // ... do stuff
        break;
    case (preg_match("/^08[0-9]{3}E$/i", $sku) ? $sku : !$sku):
        // ... do different stuff
        break;
}

What others are saying...

An excellent and very practical tip. Thank you for sharing. Here's another fun, although less practical usage. Switch against TRUE, and use the fall through to grant access in a hierarchy without repeating your code for each role and avoiding a nasty if block.
switch(TRUE) {
    case $user->is_superuser():
        $access['manage_users'] = TRUE;
        $access['write_posts']  = TRUE;
    case $user->is_admin():
        $access['moderate_comments']   = TRUE;
        $access['moderate_categories'] = TRUE;
    case $user->is_member():
        $access['write_comments'] = TRUE;
    default:
        $access['view_posts'] = TRUE;
        break;
}

Add your thoughts...

Name:

Website/URL:
(optional)

Comments:

Image Verification: