0
// Logs. Values are 0 for disabled and 1 for enabled.
define('logs', 'test');

// Display logs status.
switch(logs) {
    case 0:
        echo 'Logs are disabled.' . PHP_EOL;
        break;

    case 1:
        echo 'Logs are enabled.' . PHP_EOL;
        echo 'Location: ' . path . '\var\mailer.log' . PHP_EOL;
        break;

    default:
        echo 'Value not recognised.';
        break;
}

I was expecting as I defined the value for logs to echo the default case because it does not match 'test' value with 0 and 1 but is displaying the case 0 message.

If I change values for 0 to off and case 1 to on and I use words is working properly but for some reasons using numbers is not working.

John
  • 323
  • 1
  • 4
  • 13
  • 1
    Replace your switch block with a lookup array. https://codereview.stackexchange.com/a/216711/141885 https://stackoverflow.com/a/47785108/2943403 https://stackoverflow.com/a/47182817/2943403 – mickmackusa Apr 19 '19 at 21:32
  • It's because case is using a truthy value .. And it's saying "yes I am defined" -- You should be looking for literals in this case .. @mickmackusa's suggestion is appropriate. – Zak Apr 19 '19 at 21:33
  • Well you have to put your `case values` in quotes `" ' "`. Then it will work. – DevMan Apr 19 '19 at 21:34
  • https://stackoverflow.com/a/53797493/2943403 I have many examples to share, I'm just struggling to find the simplest one. You can search my posts for `lookup`. – mickmackusa Apr 19 '19 at 21:40
  • @mickmackusa I resolved the problem puting the cases between quotes like case '0' and case '1' – John Apr 19 '19 at 21:44
  • You may do that. I personally avoid switch blocks as much as possible because they are too verbose. – mickmackusa Apr 19 '19 at 21:46
  • @mickmackusa I think is actually much easier if I make an if statement and get over with switch – John Apr 19 '19 at 21:51
  • Here's a fresh example (using math to determine the key), but look how compact and easy to manage it is. https://stackoverflow.com/a/55768370/2943403 – mickmackusa Apr 19 '19 at 22:15

0 Answers0