PHP strcasecmp with empty string equals true?
Basically I have the code:
echo strcasecmp('hello', ' ') ? 'true' : 'false';
I don't quite understand, I'm expecting the result here to be false and not true because the string aren't equal...
Is there another better way to开发者_Go百科 compare strings in a case INSENSITIVE way?
From http://php.net/manual/en/function.strcasecmp.php
int strcasecmp ( string $str1 , string $str2 )
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.
You need to do it like
echo strcasecmp('hello', ' ') == 0 ? 'true' : 'false';
This should be
echo (strcasecmp('hello', ' ') === 0) ? 'true' : 'false';
The strcasecmp
returns 0 if both strings are equal.
http://uk3.php.net/strcasecmp
You're misinterpreting the results. What strcasecmp
returns, according to the docs is a number not equal to zero if the strings are unequal, and zero if they are equal. As you know, in PHP zero corresponds to false and non-zero corresponds to true. A proper version of your test is thus
echo (strcasecmp('hello', ' ') === 0) ? 'true' : 'false';
or, alternatively,
echo strcasecmp('hello', ' ') ? 'false' : 'true';
of which I prefer the first one, being more verbose and not containing any implicit type conversions to booleans.
精彩评论