Boolean and string condition

I need to change my status to words in the method, but when I pass the argument as a string to the method, I get the result from both conditions:

public static function Status($status)
{
    if ($status == true || $status == True  || $status == 'true' || $status == 'True' || $status == 1)
    {
        echo "true";
    }
   if ($status == false || $status == False || $status == 'false' || $status == 'False' || $status == 0)
    {
        echo "false";
    }
}

When I pass the value "False" as a string for the method, I get the result truefalse, but I have no problem with string values.

+4
source share
2 answers

You should use ===instead ==to check if this value is identical. Since any string will be considered trueif you compare it without checking the type of the variable. So change your code to

function Status($status)
{
    if ($status === true || $status === True  || $status === 'true' || $status === 'True' || $status === 1)
    {
        echo "true";
    }
    if ($status === false || $status === False || $status === 'false' || $status === 'False' || $status === 0)
    {
        echo "false";
    }
}

http://php.net/manual/en/language.operators.comparison.php

+5
source

A simple trick that may come in handy:

if (is_string($status)) $status = json_decode($status);
if ($status) {
   echo "true";
}
else {
   echo "false";
} 

json_decode 'False' 'false' false, true.

, "true" "false".

if (!is_string($status)) $status = ($status) ? "true" : "false";
echo $status;
+1

All Articles