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:45

Summing up all answers :

  • == is a bad idea for string comparisons.
    It will give you "surprising" results in many cases. Don't trust it.

  • === is fine, and will give you the best performance.

  • strcmp() should be used if you need to determine which string is "greater", typically for sorting operations.

查看更多
永恒的永恒
3楼-- · 2019-01-01 08:48

Using == might be dangerous.

Note, that it would cast the variable to another data type if the two differs.

Examples:

  • echo (1 == '1') ? 'true' : 'false';
  • echo (1 == true) ? 'true' : 'false';

As you can see, these two are from different types, but the result is true, which might not be what your code will expect.

Using ===, however, is recommended as test shows that it's a bit faster than strcmp() and its case-insensitive alternative strcasecmp().

Quick googling yells this speed comparison: http://snipplr.com/view/758/

查看更多
人气声优
4楼-- · 2019-01-01 08:57

PHP Instead of using alphabetical sorting, use the ASCII value of the character to make the comparison. Lowercase letters have a higher ASCII value than capitals. It's better to use the identity operator === to make this sort of comparison. strcmp() is a function to perform binary safe string comparisons. It takes two strings as arguments and returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal. There is also a case-insensitive version named strcasecmp() that first converts strings to lowercase and then compares them.

查看更多
孤独总比滥情好
5楼-- · 2019-01-01 08:58

Well..according to this php bug report , you can even get 0wned.

<?php 
    $pass = isset($_GET['pass']) ? $_GET['pass'] : '';
    // Query /?pass[]= will authorize user
    //strcmp and strcasecmp both are prone to this hack
    if ( strcasecmp( $pass, '123456' ) == 0 ){
      echo 'You successfully logged in.';
    }
 ?>

It gives you a warning , but still bypass the comparison.
You should be doing === as @postfuturist suggested.

查看更多
明月照影归
6楼-- · 2019-01-01 08:58

strcmp() and "===" are both case sensitive but "===" is much faster

sample code: http://snipplr.com/view/758/

查看更多
荒废的爱情
7楼-- · 2019-01-01 09:03

Also The function can help in sorting. To be more clear about sorting. strcmp() returns less than 0 if string1 sorts before string2, greater than 0 if string2 sorts before string1 or 0 if they are the same. For example

$first_string = "aabo";
$second_string = "aaao";
echo $n = strcmp($first_string,$second_string);

The function will return greater than zero, as aaao is sorting before aabo.

查看更多
登录 后发表回答