Php Switch Case无法按预期工作

时间:2018-04-25 09:51:38

标签: php nginx switch-statement php-7.1

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

我希望你能帮助我。

提前致谢。

4 个答案:

答案 0 :(得分:2)

因此,$variable0,案例$variable > 0 0 > 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;
}

答案 1 :(得分:0)

我认为你误解了开关是如何工作的。

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

所以你的脚本中发生的事情是你将$ variable(在你的例子中为0)中存储的整数值与布尔值进行比较。这是布尔方程$variable > 0的结果。 在这种情况下,你的整数值被隐式地转换为布尔值为TRUE,所以如果你插入一个数字,你的开关将始终转到你的开关的第一个案例。

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

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

答案 2 :(得分:0)

您不能在开关案例中使用比较运算符。请参阅php手册。您可以使用if语句来执行您要查找的内容。

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

答案 3 :(得分:-1)

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

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