Php Switch Case 未按预期工作

Php Switch Case not working as expected

我在一个非常基本的 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;
}

?>

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

如果我打开 url 就不是这样了:http://www.someserver.com/switch.php?variable=0

输出结果如下:

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

您输入了 0!

我希望你能帮助我。

提前致谢。

因此,$variable0,案例 $variable > 00 > 0false

比较 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;
}
switch (true) {
    case ($variable > 0):
        echo "You entered $variable!";
        break;

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

我认为您误解了开关的工作原理..

switch (VAR-TO-COMPARE){
    case VAL-TO-BE-COMOARED: do something
}

所以您的脚本中发生的事情是您将 $variable 中存储的整数值(在您的示例中为 0)与布尔值进行比较,布尔值是布尔方程 $variable > 0 的结果。 在 case 内部,您的整数值被隐式转换为 Boolean TRUE 值,因此如果您插入一个数字,您的 switch 将始终转到 switch 的第一个 case。

您可以使用 if 语句,它的可读性和效率更高

if ($variable > 0){
    do something
} else{
    do something else
}

不能在 switch case 中使用比较运算符。请参阅 php 手册。您可以使用 if 语句来执行您要查找的操作。

if($variable > 0){
  echo "You entered $variable!";
}else{
  echo "Either Your variable is less than 0, or not a Number!";
}