1

I have this method:

private function convertStatusStringToIntZeroOrOne(string $status)
{

    $status = strtolower($status);

    switch ($status) {

        case "off":
        case "0":
        case 0:
            $int_status = 0;
            break;

        case "on":
        case "1":
        case 1:
            $int_status = 1;
            break;

        default:
            $int_status = 1;
            break;


    }

    return $int_status;
}

The $status parameter, when is the string "On" (with O letter capitalize), return 0 (zero).

Of course, I need return as 1.

Thank you

1
  • 1
    Because you're doing a type juggle from string to int when testing for 0. And 'on' == 0 is true. Commented Jan 24, 2019 at 10:19

1 Answer 1

6

As you had numeric 0 and 1 in the options of the switch it was using a numeric comparison - "on" to a number is 0 and so it matched against 0.

As you have the parameter as type string a number would be converted to a string, so remove the numeric comparisons...

function convertStatusStringToIntZeroOrOne(string $status)
{
    $status = strtolower($status);

    switch ($status) {
        case "off":
        case "0":
            $int_status = 0;
            break;
        case "on":
        case "1":
            $int_status = 1;
            break;
        default:
            $int_status = 1;
            break;
    }

    return $int_status;
}
echo convertStatusStringToIntZeroOrOne("On");

Although you could reduce the function to...

function convertStatusStringToIntZeroOrOne(string $status)
{
    $status = strtolower($status);
    return ($status == "off" || $status == 0)?0:1;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Could be reduced even further to return (int) ! in_array(strtolower($status), ['off', '0'], true); - but that's less clear :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.