Advertisement
Advertisement


String comparison using '==' vs. 'strcmp()'


Question

It seems that PHP's === operator is case sensitive. So is there a reason to use strcmp()?

Is it safe to do something like the following?

if ($password === $password2) { ... }
2019/12/12
1
336
12/12/2019 10:34:26 PM

Accepted Answer

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.

2018/06/26
334
6/26/2018 1:36:18 PM


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.

2018/06/26

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.

2013/02/03

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

2016/12/21

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.

2017/10/23

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/

2011/09/26

Source: https://stackoverflow.com/questions/3333353
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]