0

The following code:

switch ($value) {
    case INF: $x = 'INF';
        break;
    case -INF: $x = '-INF';
        break;
    case NAN: $x = 'NaN';
        break;
    default: break;
}

doesn't work as I expected. I know that there are functions like is_infinite() but am I able to check variable infinity inside a switch statement?

My input can be any simple value (i.e. not an array and not an object). Could be integer, float, string, whatever.

ducin
  • 25,621
  • 41
  • 157
  • 256

1 Answers1

1

am I able to check variable infinity inside a switch statement?

No. Switch statements work with constants, not with expressions.

if (is_infinite($value) || is_nan($value)) {
  $x = (string)$value;
}

It's less lines of code, too.

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • @JoDev Preference or an actual reason? – Tomalak Mar 07 '13 at 14:22
  • PHP Manual : Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error. http://www.php.net/manual/en/control-structures.elseif.php... So it's not so important in this case! Sorry. – JoDev Mar 07 '13 at 14:25
  • @JoDev I've gotten rid of it anyway. `NAN` values become `'NAN'` automatically when cast to string. – Tomalak Mar 07 '13 at 14:30
  • PHP does allow you to use expressions in switch statements if the input is a boolean. However I would never recommend someone writing code like this, just a quirky feature. – DrBeza Mar 07 '13 at 14:33
  • @Tomalak If the value is 'test', what does $x would be at the end of your statement? is_nan return true if the given value is a string like 'test'... I think it will return 'test'. – JoDev Mar 07 '13 at 14:34
  • @JoDev Well, `$x` will be whatever it was before the `if` statement. The OP did not specify a default case, I did not specify one either. – Tomalak Mar 07 '13 at 14:48