Pregunta

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

¿Fue útil?

Solución

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.

Otros consejos

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;
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top