Re: Booleans compared to strings [message #181349 is a reply to message #181344] |
Mon, 13 May 2013 13:57 |
Robert Heller
Messages: 60 Registered: December 2010
Karma:
|
Member |
|
|
At Mon, 13 May 2013 05:29:05 -0700 (PDT) Doug Cassidy <doug(at)dougcassidy(dot)com> wrote:
>
> So, this is wierd:
>
> $b = true;
> var_dump($b);//boolean true
>
> if(!$b)echo '!$b I wont echo, correctly so<BR>';
> if($b)echo '$b I will echo, correctly so<BR>';
>
> if($b == 'false')echo '$b == I will echo, which is wrong<BR>';
> if($b === 'false')echo '$b === I wont echo, which is correct<BR>';
>
> if($b == 'true')echo '$b == I will echo, which is kinda correct<BR>';
> if($b === 'true')echo '$b === I wont echo, which is very correct<BR>';
>
> Yes, I know that 'true' and 'false' are strings, not bool.
Well, duh!
>
> this one:
> if($b == 'false')echo '$b == I will echo, which is wrong<BR>';
>
> I dont see why boolean true is equal to string false in any way.
Any non empty value (including a non empty string) is true, therefore "$b ==
'false'" evaluates to true. Live with it.
PHP is using the *C* convention with respect to booleans. 0 is false, and any
non-zero value is true. A NULL pointer (eg an empty string) is effectively the
same as a numeric value of 0, and is thus false also. Any non-NULL pointer (eg
any object, array, or string) is effectively the same as a non 0 numeric
value, and is thus true.
Why in the world are you comparing booleans to strings? If this is a
string-based parameter setting, you should be just comparing the strings and
not be using booleans at all. Or you should not be using string-based
parameter settings for boolean parameters. Or you need to write a suitable
checking function that does an 'intellegent' type casting that suits the use
case you are handling. Something like:
function string_to_boolean($string) {
switch ($string) {
case 'true':
case 'yes':
case '1':
case 1:
case true:
return true;
case 'false':
case 'no':
case '0':
case 0:
case false:
return false;
default:
if (empty($string)) {
return false;
} else {
return true;
}
}
}
Then:
if ($b == string_to_boolean('false')) echo '$b == string_to_boolean(\'false\') I wont echo, which is correct<BR>';
Will behave as expected.
--
Robert Heller -- 978-544-6933 / heller(at)deepsoft(dot)com
Deepwoods Software -- http://www.deepsoft.com/
() ascii ribbon campaign -- against html e-mail
/\ www.asciiribbon.org -- against proprietary attachments
|
|
|