Multiple cases for switch construct

Posted in Programming  
E-Mail This Post/Page   

Looking at the PHP documentation, it is not clear how to add multiple values for the same case in a switch construct. It seems that you should be able to do

PHP:
  1. case ("whatever" || "something"):
  2. //Do something;
  3. break;

But, you can't. I tried, and it didn't work. Fortunately, after much searching, I found a way to do it; and it's not near as difficult as I was making it.

Let's look at this code:

PHP:
  1. switch (value)
  2.     {
  3.     case 1:
  4.         echo "Value was 1";
  5.         break;
  6.     case 2:
  7.     case 3:
  8.         echo "Value was 2 or 3";
  9.         break;
  10.     case 4
  11.         echo "Value was 4";
  12.         break;
  13.     default:   
  14.         echo "Value was not 1-4";
  15.         break;
  16.     }

It works. If the value is either 2 or 3 it echoes out the same string. This takes advantage of not putting in the break; statement after the case 2: line.

The next step is to allow a range, and I'm still looking for that... If you have any thoughts, stick it in a comment :-)

Difference in Hub, Switch, Bridge, & Router
DIY: Make Your Own Ethernet Loopback Cable
Your color laser printer may be keeping track of you
Review: D-Link 604 Router
Penn state urges students to dump Internet Explorer

2 Comments on “Multiple cases for switch construct”

Bruno on

I’ve discovered the syntax which makes the multiple-construct work:

You simply omit the parenthesis, so that the case line reads eg:

case 1 || 2:
echo “foobar”;

and so on.

It seems that the range allows something like this:

case 1-3:
echo “foobar”;

Ryan on

The OR construct seems to work for me, but the range doesn’t.

Leave a Comment