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.

13
  • 2
    @MichaelBerkowski How do you know OP isn't possibly passing a string to the switch? Commented Sep 15, 2017 at 17:38
  • 5
    Long story short, PHP will cast strings to integers, resulting in 0 when comparing. Your input $state must be a string type to avoid the cast and incorrect comparison. It cannot be an int. echo 0 == "any string" prints 1. Commented Sep 15, 2017 at 17:42
  • 2
    If int 0 is valid input, why not cast it to a string, make it a case, put it first and don't rely on the default? Commented Sep 15, 2017 at 17:45
  • 4
    But of course you can force a cast to string, and get the result you want: switch ((string)$state). Commented Sep 15, 2017 at 17:45
  • 1
    ^^ Yes. Force $state to be a string before allowing it to pass into the switch. That should solve this. Commented Sep 15, 2017 at 17:45

1 Answer 1

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)
...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.