首页 > 解决方案 > Php Switch Case 未按预期工作

问题描述

我在一个非常基本的PHP脚本中犯了一个非常愚蠢的逻辑错误。

有关结论,请参见 u_mulders 答案。

脚本访问一个 $_GET[] 变量,并且应该只确定该变量是否已设置(非常有效)以及它是否设置为大于 0 的值(这未按预期工作)。

这里是“switch.php”文件:

<?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;
}

?>

现在我希望第一个 case-Statement 仅在 $variable 大于 0 时运行。

如果我打开网址,情况并非如此:http ://www.someserver.com/switch.php?variable=0

输出如下:

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

您输入了 0!

我希望你能帮助我。

提前致谢。

标签: phpnginxswitch-statementphp-7.1

解决方案


所以, $variableis 0, case $variable > 0which 0 > 0is false

比较0false。你得到了什么?当然——真的。

重写你switch的:

// 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;
}

推荐阅读