0

I would like to differ between the following cases in PHP using a switch statement. Can someone here help and tell me how I have to change this to get it working with numeric ranges (integers) ?

  • $myVar < 0
  • $myVar < 10
  • $myVar < 20
  • $myVar < 30
  • $myVar < 999
  • default

So far I have the following but guess this needs modification because of the ranges:

switch($myVar)
{
    case(<0):
        // do stuff
        break;
    case(<10):
        // do stuff
        break;
    case(<20):
        // do stuff
        break;
    case(<30):
        // do stuff
        break;
    case(<999):
        // do stuff
        break;
    default:
        // do stuff
        break;
}

Many thanks for any help with this, Tim

user2571510
  • 11,167
  • 39
  • 92
  • 138

2 Answers2

2

You can do it like this:

$myVar = 50;
switch (true) {
    case($myVar < 0):
        // do stuff
        break;
    case($myVar < 10):
        // do stuff
        break;
    case($myVar < 20):
        // do stuff
        break;
    case($myVar < 30):
        // do stuff
        break;
    case($myVar < 999):
        // do stuff
        break;
    default:
        // do stuff
        break;
}

There are a few good example about that in the comments of the manual.

Bjoern
  • 15,934
  • 4
  • 43
  • 48
  • One follow-up question on this, would this work the same way in JavaScript as well ? – user2571510 Feb 11 '14 at 20:53
  • 1
    Check out this SO answer: http://stackoverflow.com/questions/17145723/how-can-i-use-ranges-in-a-switch-case-statement-using-javascript There you'll find a good source for this additional question. – Bjoern Feb 11 '14 at 20:59
1

Use the in_array($myVar,range(100,200)) to check whether the value exists in the range.

$myVar = 50;
switch (true) {
    case(in_array($myVar,range(0,10))):
        // do stuff
        break;
    case(in_array($myVar,range(20,30))):
        // do stuff
        break;
    case(in_array($myVar,range(30,900))):
        // do stuff
        break;

    default:
        // do stuff
        break;
}
Nambi
  • 11,944
  • 3
  • 37
  • 49