Skip to content

Multiple cases for switch construct

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

case ("whatever" || "something"):
//Do something;

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:

switch (value)
	case 1:
		echo "Value was 1";
	case 2:
	case 3:
		echo "Value was 2 or 3";
	case 4:	
		echo "Value was 4";
		echo "Value was not 1-4";

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 :-)

Published inProgramming


  1. Bruno Bruno

    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”;

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

  3. Thierry Thierry

    After working around with the same question, I think I give some kind of explanations, a little different from the provious ones.

    switch doesn’t act differently with strings.

    This work fine:

    case “A”:
    case “B”:
    case “C”:
    case “D”:
    $L = “ABCD”;

    case “E”:
    case “F”:
    case “G”:
    case “H”:
    $L = “EFGH”;

  4. Jeff Jeff

    Multiple cases within parenthesis as described by Thierry worked fine for me , Thanks for the information helped a lot

  5. Gordon Gordon

    For a range, use the two statements construct with > and 0:
    case $daysold<31:
    'This is between 0 and 31 days old'

  6. if i understand your question, i’m thinking that for a range you can just use…

    //range 12-21
    case ( $value >= 12 && $value <= 21 ):
    //code to execute goes here


    You also may also use that for comparison. For example, we measure the script execution time and generate a comment about it. $totaltime is number of seconds script executes.


    switch ($totaltime) {

    case ($totaltime 1):
    echo “Not fast!”;

    case ($totaltime > 10):
    echo “That’s slooooow”;


    • Been a while since I wrote this, but I think my mind was in Java mode about the ranges.

  7. Dan Brown Dan Brown

    Its a shame you can’t do nested php so that you can echo out the php code… like a php preprocessor that returns php to be parsed by the php :) You could use that to echo multiple case x: case x+1 …etc. Not a particularly nice way of doing it, but it would be cool if you could.

  8. Nam Nam

    Thank you! It works!

Leave a Reply

Your email address will not be published. Required fields are marked *