用于空字符串的php开关

用于空字符串的php开关,php,switch-statement,Php,Switch Statement,对于以下带有switch语句的php程序,为什么“”给我$vSS=2而不是=1? 我觉得很奇怪。我使用的是PHP5.5.9。 我可以添加case“”:来解决这个问题,但我很好奇为什么PHP给出$vSS=2而不是 $vSS=1。这是正常的还是错误的 <?php R(15); // 1 ok R(''); // why give me 2 R(40); // 2 ok R(70); // 3 ok # function R($SS){ switch($SS){

对于以下带有switch语句的php程序,为什么“”给我$vSS=2而不是=1? 我觉得很奇怪。我使用的是PHP5.5.9。 我可以添加case“”:来解决这个问题,但我很好奇为什么PHP给出$vSS=2而不是 $vSS=1。这是正常的还是错误的

<?php
  R(15); // 1 ok
  R(''); // why give me 2
  R(40); // 2 ok
  R(70); // 3 ok
#
  function R($SS){
    switch($SS){
      case $SS<=20: $vSS=1;break;
      case ($SS>20 and $SS<=49.9): $vSS=2;  // why here?
        if($SS == '') echo "DEBUG: SS is a null string.<br>\n";
        break;
      case ($SS<=100 and $SS>49.9): $vSS=3; break;
      default:$vSS=0 ;
    }
    echo "DEBUG:(SS/vSS) $SS:$vSS\n";
  }
?>

------ RESULT
DEBUG:(SS/vSS) 15:1
DEBUG: SS is a null string.<br>
DEBUG:(SS/vSS) :2
DEBUG:(SS/vSS) 40:2
DEBUG:(SS/vSS) 70:3

------结果
调试:(SS/vSS)15:1
调试:SS是空字符串。
调试:(SS/vSS):2 调试:(SS/vSS)40:2 调试:(SS/vSS)70:3
您不了解
开关的工作原理。它将
开关($SS)
中的值与每个
案例
值进行比较,它不仅仅测试每个
案例
。所以

switch ($SS) {
case $SS<=20:

@Barmar是对的,
case()
中的表达式与
switch(这里的某物)
相比较,但您不必将所有代码都转换为
if/elsif/elsif/../../../../-/code>逻辑。只需将
switch()
语句更改为
true

switch(true) { // <-- this part only
  case $SS<=20:
      $vSS=1;
      break;
  case ($SS>20 and $SS<=49.9):
    $vSS=2;  // why here?
    // must not be here
    // if($SS == '') echo "DEBUG: SS is a null string.<br>\n";
    break;
  case ($SS<=100 and $SS>49.9):
      $vSS=3; 
      break;
  case $SS=='': // you can check it here
      echo "DEBUG: SS is a null string.<br>\n";
      break;
  default:
      $vSS=0 ;
}
switch(true){/
function R()
echo“DEBUG:(SS/vSS)$SS:$vSS\n”
噢,我喜欢它。@Barmar是对的,
switch-case
不是这样工作的
if ($SS <= 20) {
    $vSS = 1;
} elseif ($SS <= 49.9) {
    $vSS = 2;
} else {
    $vSS = 0;
}
switch(true) { // <-- this part only
  case $SS<=20:
      $vSS=1;
      break;
  case ($SS>20 and $SS<=49.9):
    $vSS=2;  // why here?
    // must not be here
    // if($SS == '') echo "DEBUG: SS is a null string.<br>\n";
    break;
  case ($SS<=100 and $SS>49.9):
      $vSS=3; 
      break;
  case $SS=='': // you can check it here
      echo "DEBUG: SS is a null string.<br>\n";
      break;
  default:
      $vSS=0 ;
}