Pedram marandi
Pedram marandi

Reputation: 1614

Boolean and string condition

I have to change my status to words in a method but when I pass argument as a string to the method, I get result from both of the 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 'False' value as string to the method I get truefalse result but I don't have any problems with string values.

Upvotes: 4

Views: 854

Answers (2)

Devon Bessemer
Devon Bessemer

Reputation: 35357

A simple trick that might come in handy:

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

json_decode will convert 'False' or 'false' into a boolean false, same with true.

Another way of doing this would be to leave strings alone, so convert booleans and integers to the string 'true' and 'false'.

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

Upvotes: 1

ihsan
ihsan

Reputation: 2289

You should use === instead of == to check if the value is identical. Because any string will be considered as true if compared without checking variable type. 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

Upvotes: 5

Related Questions