doulai5585
doulai5585
2017-03-01 12:20
浏览 31
已采纳

值为零时PHP脚本错误

I not understand little bit. Simple switch statement not working correctly with zero value (=0):

//$result = $sql->fetchColumn(); 
$result = 1;
      switch ($result) {    
          case $result <= 2 :
              throw new Exception('Error!');
              break;
                        }

Problem is when $result = 0 then output should be 'error' but in this case script passing this validation. Weird question but i can't find a problem.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dqpc1845
    dqpc1845 2017-03-01 12:27
    已采纳

    You can write it like that:

    <?php
    switch ($i) {
    case 0:
    case 1:
    case 2:
        throw new Exception('Error!');
        break;
    case 3:
        echo "i is 3 or higher.";
    }
    ?>
    

    As I said in my comment above, you can't use "grater than" "less than" etc. in a switch-statement. As other said, if you want to make use of them, use a simple IF statement.

    点赞 评论
  • douxie3625
    douxie3625 2017-03-01 12:38

    this code

    switch ($result) {    
          case $result <= 2 :
    

    is equivalent

    if($result == ($result <= 2))
    

    and when

    $result=0 
    

    we have

    ( 0 == true ) 
    

    after type conversion

    false === true
    

    and this is false as expected

    点赞 评论

相关推荐