PHP fugly bug on case switch statement - PHP version 7.0.13

Everything works fine if $value is greater than 0 but if $value is set to 0 then case switch prints Billion :-).

Since the manual does not state that value 0 is not evaluated then this is a fugly bug to me. http://php.net/manual/en/control-structures.switch.php

$value = 0;

    switch ($value) {
    case $value >= 1000000000:
      print 'Billion'; 
      break;
    case $value >= 1000000:
      print 'Million';
      break;
    case $value >= 1000 :
      print 'Thousand';
      break;
    default:
          print 'Ten';
      break;            
    }      

.

Output: Billion  :-)

3 answers

  • answered 2018-04-17 06:08 Aniket Sahrawat

    It is because switch case does not take expressions that can be evaluated. You should use if else for this. Eg of switch case:

    $value = 2;
    switch($value) {
        case 2:
            print "two";
        break;
        default:
            print "default";
    }
    

    Eg of if else:

    $value = 3;
    if( $value > 2 ) {
        print "greater than 2";
    } elseif($value > 1) {
        print "greater than 1";
    } else {
        print "default";
    }
    

  • answered 2018-04-17 06:13 Mohammad Wasim

    $value = 0;
    
        switch (true) {
        case ($value >= 1000000000):
          print 'Billion'; 
          break;
        case ($value >= 1000000):
          print 'Million';
          break;
        case ($value >= 1000) :
          print 'Thousand';
          break;
        default:
              print 'Ten';
          break;            
        }  
    

    please refer this answer https://stackoverflow.com/a/7801218/6186468

  • answered 2018-04-17 06:19 Md Rashed Pervez

    switch statements perform equality tests on the values in the cases. PHP is evaluating your comparisons, so $value = 0 becomes case false. false is considered to be equal to 0, so the first case matches.

    $value = 0;
    
    switch (true) {
    case ($value >= 1000000000):
      print 'Billion'; 
      break;
    case ($value >= 1000000):
      print 'Million';
      break;
    case ($value >= 1000) :
      print 'Thousand';
      break;
    default:
          print 'Ten';
      break;            
    }