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条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器