Is this a bug in PHP SWITCH?

-1

I'm trying to make a switch in PHP, but it returns me some very strange values.

For example, if the variable $xp is equal to 0 , it returns me that the level is 20 .

I'm not understanding '-'

switch($xp){
        case($xp <= 60);
        $nivel = 0;
        break;

        case($xp <= 200);
        $nivel = 1;
        break;

        case($xp <= 350);
        $nivel = 2;
        break;

    //... vários case dps.

        case($xp <= 4375);
        $nivel = 18;
        break;

        case($xp <= 5000);
        $nivel = 19;
        break;

// se $xp for igual a 0 ele me retorna $nivel = 20
        case($xp > 5000);
        $nivel = 20;
        break;
    }

$xp is returned from the database, it is INT .

    
asked by anonymous 05.07.2018 / 21:48

2 answers

9

There are no bugs in switch . The problem lies in the logic of your code. For, for all cases, it is returning true since 0 is less than any of the values of its cases, with the exception of $xp > 5000 . Therefore, it is returning the assignment of the last case. If you remove case($xp > 5000) , you will see that the $nivel value will be 19.

In your case, the ideal, however intuitive it may seem, is to use if and else if , due to the range you are using. The switch is used in the case of cases , such as the switch of a lamp, the selector of a washing machine, etc.

You could even use the switch structure, but your code would probably be too large and impractical, it would look something like this:

switch($xp){
    case(60): case(61): case(62): case(...): case(199):
        $nivel = 0;
        break;
    case(200): case(201): case(202): case(...): case(499):
        $nivel = x;
        break;
    ....
    default:
        break;

With else if :

if($xp > 0 && $xp < 200){
    $nivel = 0;
}else if($xp > 200 && $xp < 500){
    $nivel = x;
}
    
05.07.2018 / 22:03
0

The reason for the error has already been explained, and what you want is not with switch , but that does not mean that a lot of if else is the best option

An example with an array and a loop:

//Crie um array em que as chaves são
//os níveis e os valores serão o que
//irá usar para comparar
$array = [
  0 => [0, 60],
  1 => [60, 200],
  2 => [200, 350]
  //...
];

//Por padrão o nível vai ser 20, seria como um else
$nivel = 20;

//Percorre o array e verifica o valor da
//variável $xp com as chaves
foreach ($array as $chave => $valor) {
  //Se o $xp for > ou = ao primeiro numero do $valor
  //e for menor que o segundo numero do $valor
  if ($xp >= $valor[0] && $xp < $valor[1]) {
    //A variavel $nivel recebe a chave
    $nivel = $chave;
  }
}

So you only have one condition (which will be executed once for each item inside the loop), if you need to add a new level or change the old one, just update the array

In this case the keys of $array would not need to be set explicitly, but I left it for better understanding

    
25.10.2018 / 14:30