douzhong6480 2018-04-25 09:51
浏览 88
已采纳

Php Switch Case无法按预期工作

I made a pretty stupid Logic Error in a very Basic PHP Script.

See u_mulders Answer for the Conclusion.

The Script accesses a $_GET[] Variable and should just determine if the Variable is set (wich works) and if its set to a value above 0 (this is not working as expected).

Here comes the "switch.php" File:

<?php

if($_GET["variable"]==NULL){
    die('Set $_GET["variable"] to use this Script!');
}

//Create Instance of $_GET["variable"] casted to Integer
$variable = (integer)$_GET["variable"];

//this var_dump displays that the $variable is succesfully casted to an Integer
var_dump($variable);

switch ($variable) {
    case ($variable > 0):
        echo "You entered $variable!";
        break;

    default:        
        echo "Either Your variable is less than 0, or not a Number!";
        break;
}

?>

Now I expected the first case-Statement to only run if $variable is greater than 0.

This is not the Case if I open the url: http://www.someserver.com/switch.php?variable=0

The Output is as follows:

.../switch.php:11:int 0

You entered 0!

I hope You can help me.

Thanks in advance.

  • 写回答

4条回答 默认 最新

  • dsbtwy1329 2018-04-25 09:54
    关注

    So, $variable is 0, case $variable > 0 which is 0 > 0 is false.

    Compare 0 and false. What do you get? Of course - true.

    Rewrite your switch to:

    // compare not `$variable` but result of some operation with `true`
    switch (true) {           
        case ($variable > 0):
            echo "You entered $variable!";
            break;
    
        default:        
            echo "Either Your variable is less than 0, or not a Number!";
            break;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!