switch does not show expected result

-5

What's wrong? It was supposed to appear "worthless", but when it starts with zero it appears "too high" in the message.

<?php
$num = 0;

switch ($num){
    case($num>100);
        echo'valor muito alto';
        break;
    case($num<80 && $num>51);
        echo'valor medio';
        break;
    case($num==50);
        echo'valor perfeito';
        break;
    case($num<=10);
        echo'valor muito baixo';
        break;
    case($num==0);
        echo'sem valor';
        break;
}
?>
    
asked by anonymous 04.11.2014 / 23:52

2 answers

12

case does not work the way you expect it to. It is not a replacement for if . See the documentation . The case only accepts a value, it only tests the equality of that value.

More or less what you want is this:

$num = 0;
if ($num > 100) echo 'valor muito alto';
else if ($num < 80 && $num > 51) echo 'valor medio';
else if ($num == 50) echo 'valor perfeito';
else if ($num <= 10) echo 'valor muito baixo';
else if ($num == 0) echo'sem valor';

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

There is still a logic error there. You can not even understand what the goal is. It has overlapping ranges of values, ranges of values that are not reached by any of the conditions.

    
05.11.2014 / 00:10
0

I tested it here and it worked, it is a gambiarra, but it meets your need, as I want to test more than one value in the case, I have to create an array like @Miero said, the case It does not work like that, but you can play a game.

Creating 3 arrays with the range of values you want, and testing whether the value exists inside the array using the in_array function, is nice ...

<?php
    $num = 40;

    $array100_80 = array();
    $array79_51 = array();
    $array49_1 = array();

    for ($i = 80; $i <= 100; $i++) {
        $array100_80[$i] = $i;
    }

    for ($i = 51; $i <= 79; $i++) {
        $array79_51[$i] = $i;
    }

    for ($i = 1; $i <= 49; $i++) {
        $array49_1[$i] = $i;
    }

    switch ($num){
        case(0):
            echo'sem valor';
            break;
        case(in_array($num, $array100_80)):
            echo'valor muito alto';
            break;
        case(in_array($num, $array79_51)):
            echo'valor medio';
            break;
        case(50):
            echo'valor perfeito';
            break;
        case(in_array($num, $array49_1)):
            echo'valor muito baixo';
            break;
    }
    
05.11.2014 / 13:26