String comparison using == vs. strcmp

2019-01-01 08:31发布

It seems that PHP's === operator is case sensitive? So is there any reason to use strcmp()? Is it safe to do something like:

if ( $password === $password2 ) { ... }

标签: php
12条回答
栀子花@的思念
2楼-- · 2019-01-01 08:38

You can use strcmp() if you wish to order/compare strings lexicographically. If you just wish to check for equality then == is just fine.

查看更多
栀子花@的思念
3楼-- · 2019-01-01 08:40

The reason to use it is because strcmp

returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal.

=== only returns true or false, it doesn't tell you which is the "greater" string.

查看更多
浮光初槿花落
4楼-- · 2019-01-01 08:41

Always remember, when comparing strings, you should use === operator (strict comparison) and not == operator (loose comparison).

查看更多
冷夜・残月
5楼-- · 2019-01-01 08:41

strcmp will return different values based on the environment it is running(Linux/Windows)!

The reason is the that it has a bug as the bug report says https://bugs.php.net/bug.php?id=53999

Please handle with care!!Thank you.

查看更多
何处买醉
6楼-- · 2019-01-01 08:44

You should never use == for string comparison. === is OK.

$something = 0;
echo ('password123' == $something) ? 'true' : 'false';

Just run the above code and you'll see why.

$something = 0;
echo ('password123' === $something) ? 'true' : 'false';

Now, that's a little better.

查看更多
公子世无双
7楼-- · 2019-01-01 08:44

Don't use == in PHP. It will not do what you expect. Even if you are comparing strings to strings, PHP will implicitly cast them to floats and do a numerical comparison if they appear numerical.

For example '1e3' == '1000' returns true. You should use === instead.

查看更多
登录 后发表回答