jjkao
jjkao

Reputation: 13

php switch for a null string

For the following php program with a switch statement, why '' give me $vSS=2 instead of =1? Quite strange to me. I am using PHP 5.5.9. I can add case '': to resolve the problem, but I am curious why PHP give $vSS=2 instead of $vSS=1. Is it normal or a bug?

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

Upvotes: 1

Views: 2982

Answers (2)

vladkras
vladkras

Reputation: 17228

@Barmar is right, expression in case() is compared to switch(something_here) but you don't have to cahnge your all your code to if/elsif/elsif/.../... logic. Just change switch() statement to 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 ;
}

Upvotes: 1

Barmar
Barmar

Reputation: 781225

You don't understand how switch works. It compares the value in switch($SS) with each of the case values, it doesn't just test each case. So

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

is similar to:

if ($SS == ($SS<=20))

The reason the second case is being executed is because ($SS > 20 && $SS <= 49.9) is false, and false is considered equal to zero or an empty string.

You shouldn't use switch for what you're doing, you should use if/then/elseif/else:

if ($SS <= 20) {
    $vSS = 1;
} elseif ($SS <= 49.9) {
    $vSS = 2;
} else {
    $vSS = 0;
}

Upvotes: 2

Related Questions