1

PREAMBLE: $state can have 3 possible values:

  • 1) 0 (zero , int)
  • 2) 'Set Level: 10 %' (string)
  • 3) 'Set Level: 20 %' (string)

I have a switch code that doesn't return right value.

This is the code:

<?php

$state = 0;

switch ($state) {

            case 'Set Level: 10 %':

                $return = 1;

            break;

            case 'Set Level: 20 %':

                $return = 2;

            break;

            default:

                $return = 0;

            break;

        }

        echo 'return:';

        var_dump($return);

And this is the fiddle: https://3v4l.org/IQ142

With $state = 0 it returns 1 and not 0, as default. I did try also to remove default and impose case 0: but no change.

Thank you

NOTICE: $state could be also as string. For this I need to check for string.

Barmar
  • 741,623
  • 53
  • 500
  • 612
sineverba
  • 5,059
  • 7
  • 39
  • 84

1 Answers1

5

You can not compare an int with a string. Before sending the $state to the switch do a conversion to string. This will give you the correct result.

$state = 0;

switch((string)$state)
...
Leonardo
  • 218
  • 2
  • 7