Search code examples
phpswitch-statementrangenumeric-ranges

PHP: issue with switch with range


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


Solution

  • 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.