Jump to content

Case statement not working


EchoFool

Recommended Posts

hey

 

I have a case statement that returns the wrong answer when its checking a value which is 0. Which makes no sense as all other values work fine.

 

This is my case statement:

 

   

$Var = 0;
    switch($Var) {
    case ($Var < 100): $Answer = 'step 1'; break;
    case ($Var > 99 && $Var < 200): $Answer = 'step 2'; break;
    case ($Var > 199  && $Var < 300): $Answer = 'step 3'; break;
    case ($Var > 299  && $Var < 400): $Answer = 'step 4'; break;
    case ($Var > 399): $Answer = 'step 5'; break;
    default: $Answer = 'step default';
    }

 

For input value 0 i get "Step 2" as a reply when it should "Step 1".

 

I got no idea why this is the case, given it should not be showing step 2.. can some one explain please. Thanks.

Link to comment
https://forums.phpfreaks.com/topic/207048-case-statement-not-working/
Share on other sites

When you use conditions for cases in a switch statement, you should switch on "true":

<?php
    $Var = 0;
    switch(true) {
    case ($Var < 100): $Answer = 'step 1'; break;
    case ($Var > 99 && $Var < 200): $Answer = 'step 2'; break;
    case ($Var > 199  && $Var < 300): $Answer = 'step 3'; break;
    case ($Var > 299  && $Var < 400): $Answer = 'step 4'; break;
    case ($Var > 399): $Answer = 'step 5'; break;
    default: $Answer = 'step default';
    }
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.