359

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) { ... }
10
  • 12
    What's case-sensitivity have to do with strcmp?
    – kennytm
    Commented Jul 26, 2010 at 8:50
  • 2
    @KennyTM: strcmp is case-sensitive. In some languages, like VB, string comparison may not be, and thus would return a different result. This isn't the case in PHP, though.
    – cHao
    Commented Jul 26, 2010 at 8:56
  • 14
    @jie: You may want to use === instead of == because '0XAB' == '0xab' is true.
    – kennytm
    Commented Jul 26, 2010 at 9:01
  • 17
    to use === instead of == is important, because comparing any string to 0 with == will return true which is obviously false...
    – Karl Adler
    Commented Jan 27, 2013 at 8:37
  • 4
    @Kenny Also '0xAB' == '171'
    – Antimony
    Commented Dec 1, 2014 at 6:52

15 Answers 15

351

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.

9
  • 9
    icic tho in my current case, i dont need to know which string is greater :)
    – Jiew Meng
    Commented Jul 26, 2010 at 9:11
  • 168
    strcmp with matching strings took 0.207852 seconds strcmp with non-matching strings took 0.215276 seconds === with matching strings took 0.067122 seconds === with non-matching strings took 0.057305 seconds snipplr.com/view/758
    – user503853
    Commented Apr 22, 2013 at 17:00
  • 3
    The other usage for strcmp it shows the sorting. To be more clear about sorting. strcmp() returns <0 if string1 sorts before string2, >0 if string2 sorts before string1 or 0 if they are the same. For example $string_first = "aabo"; $string_second = "aaao"; echo $n = strcmp($string_first,$string_second); will return greater than zero, as aaao is sorting before aabo.
    – HTML Man
    Commented Aug 16, 2013 at 18:00
  • 23
    Why does this answer get the most upvotes? I'm downvoting because although it's the answer that this question deserves but not the 'right' answer. Right answer should be 'Use ===' as a lot of people already said in other answers. Commented Nov 8, 2013 at 8:14
  • 5
    @onur güngör Actually, this does answers the op's question, which is So is there any reason to use strcmp() ?, while Postfuturist's answer doesn't. Oh, hell... no one answer seemed to compile at once the use of strcmp(), the performance of ===, and the bad reliability of == for string comparisons... so I added mine to the list.
    – Balmipour
    Commented Aug 31, 2017 at 17:19
228

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.

9
  • 20
    == isn't just a problem for differing types. It will sometimes give unexpected results even if both sides are a string. Try '1e3' == '1000'
    – Antimony
    Commented Jun 21, 2012 at 1:54
  • 3
    how does 0 == 'password123' ?
    – Andy Lobel
    Commented Aug 10, 2012 at 2:41
  • 26
    @AndyLobel PHP coerces 'password123' to a number using it's odd loose comparison rules since the other operand is a number, that string, like most, coerces to the number 0, and PHP returns true for the comparison. Commented Aug 10, 2012 at 5:15
  • 9
    A quick var_dump((int)'password123'); helped me fully understand why this happened...**embarrassed**...I really like the === operator
    – Carlton
    Commented Nov 8, 2012 at 11:49
  • 4
    this is beacuse using '==' if one of the two operands is castable to number, php casts both the operands to numbers, and more, if a not number string is casted to number, it takes value zero, resulting equals to zero, so the result of the comparison with simple '==' can something unwanted
    – Luca C.
    Commented Aug 1, 2014 at 6:29
107

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.

2
  • 11
    @Roman yes but a lot of PHP programmers don't know they have to do that. Hence the warning.
    – Antimony
    Commented Jan 25, 2013 at 4:36
  • 6
    @Antimony So why not tell them what they should do in your answer?
    – Tim
    Commented Mar 8, 2018 at 16:19
44

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.

4
  • 6
    Wow +1. Quote from the link: "It is established behavior for function that receive the wrong type of argument(s) to return null". That's amazing considering the manual just says this: "Returns < 0 if str1 is less than str2; > 0 if str1 is greater than str2, and 0 if they are equal". Null is not mentioned as a possibility, yet on pages such as the substr man page it is mentioned. sigh
    – Gerry
    Commented Jul 4, 2013 at 17:32
  • But does the same happens when the form method is post ...?
    – nkg
    Commented Feb 28, 2014 at 18:44
  • @NikhilGeorge It does, the function in question here is strcmp. It doesn't matter which inputs are being compared against.
    – Ajith
    Commented Oct 11, 2014 at 19:52
  • 1
    While the bug report says it was fine to return null, this is incorrect. All official PHP releases from PHP 4.3 to PHP 7.3 do not return null from these functions. I suspect it may've been an alpha or beta release, and regardless of the bug being closed is invalid, it was fixed. See 3v4l.org/Zq8tM for details, which show that it does affect HHVM 3.11 - 3.19. Commented Jun 26, 2018 at 13:46
36

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

1
  • 8
    Actually, I think it's safe to say that you should use === when comparing anything. Commented Jun 9, 2015 at 22:37
27

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.

21

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
  • 1
    Sometimes it casts them to a different type even if they already have the same type.
    – Antimony
    Commented Apr 25, 2013 at 5:24
  • even when comparing two strings that represented an integer like "012" == "12" php changed the type of both strings to integer 12 == 12 and then returned true.
    – GoTo
    Commented Sep 23, 2014 at 18:09
  • @GoTo: Didn't that change in some later PHP version? Commented Sep 17, 2021 at 20:20
  • @PeterMortensen No idea. Currently I don't write PHP.
    – GoTo
    Commented Sep 18, 2021 at 11:39
14

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

Sample code: Speed Test: strcmp vs ===

6

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

The reason is the that it has a bug as the bug report says - Bug #53999strcmp() doesn't always return -1, 0, or 1

1
  • It will always return 0 if the strings are equal, though. +1 for being careful about caring about any other value than 0 though. Commented Mar 26, 2013 at 10:05
5

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

4
  • 1
    Like in usort. In fact, it's pretty much made for sorting.
    – Charles
    Commented Jul 26, 2010 at 8:46
  • @Charles Thanks. Wikipedia made my eyes glaze over.
    – cbednarski
    Commented Jul 26, 2010 at 8:51
  • 1
    To be more clear about sorting. strcmp() returns <0 if string1 sorts before string2, >0 if string2 sorts before string1 or 0 if they are the same. For example $string_first = "aabo"; $string_second = "aaao"; echo $n = strcmp($string_first,$string_second); will return greater than zero, as aaao is sorting before aabo.
    – HTML Man
    Commented Aug 16, 2013 at 17:58
  • @postfuturist I'm sure it's a typo and they meant ===.
    – Ash
    Commented Mar 29, 2016 at 16:17
4

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.

1

if ($password === $password2) { ... } is not a safe thing to do when comparing passwords or password hashes where one of the inputs is user controlled.
In that case it creates a timing oracle allowing an attacker to derive the actual password hash from execution time differences.
Use if (hash_equals($password, $password2)) { ... } instead, because hash_equals performs "timing attack safe string comparison".

2
  • What is "timing oracle"? Padding oracle attack? Or something else? Can you add some references? (But without "Edit:", "Update:", or similar - the answer should appear as if it was written today.) Commented Feb 1, 2022 at 23:56
  • @Peter Mortensen: A timing oracle attack is comparing the execution times of the same operation done with different inputs. $a === $b completes as soon as difference is detected, while hash_equals explicitly keeps comparing the remainder even though the result is already known. So for the latter, execution time is independent of original input when comparing hashes (which always have the same length regardless of input).
    – Oktokolo
    Commented Feb 3, 2022 at 9:55
0

In 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.

0

Nowadays, for comparing two strings, use collator_compare instead. It works with Unicode and it's more flexible than strcmp or strcasecmp. Those two legacy functions give strange results for non-trivial inputs and the documentation is misleading on them returning straightforward values like -1, 0, or 1.

Here is the first example from the documentation for collator_compare:

<?php
$s1 = 'Hello';
$s2 = 'hello';

$coll = collator_create( 'en_US' );
$res  = collator_compare( $coll, $s1, $s2 );

if ($res === false) {
    echo collator_get_error_message( $coll );
} else if( $res > 0 ) {
    echo "s1 is greater than s2\n";
} else if( $res < 0 ) {
    echo "s1 is less than s2\n";
} else {
    echo "s1 is equal to s2\n";
}
?>

Note: the PHP intl extension is required.

0

String comparison in Hebrew is tricky because of the order of nekudot (punctation). These two words seems to be perfectly equal, but they are not as the order of nekudot (diacritics) is switched.

echo "What is strcmp() good for?";
$first="כֻּלָּן";
$second="כֻּלָּן";
echo "<pre>first&nbsp;&nbsp;$first ". bin2hex($first )."";
echo "<br>second $second ". bin2hex($second)."";
echo "<br>first  כֻּלָּן d79bd6bcd6bbd79cd6b<b>cd6b8d</b>79f";
echo "<br>second כֻּלָּן d79bd6bbd6bcd79cd6b<b>8d6bcd</b>79f</pre>";
echo "<p><b>==</b></p>"; //not eqal
if ($first==$second) {
echo "<p>$first is eqal the $second</p>";
} else {
echo "<p>$first not eqal the $second</p>";
}
echo "<p><b>===</b></p>";
if ($first===$second) { //not equal
echo "<p>$first is eqal the $second</p>";
} else {
echo "<p>$first not eqal the $second</p>";
}
echo "<p><b>strcmp</b></p>";
if (strcmp($first, $second)) { //equal
echo "<p>$first is eqal the $second</p>";
} else {
echo "<p>$first not eqal the $second</p>";
}

Output:

first כֻּלָּן d79bd6bcd6bbd79cd6bcd6b8d79f

second כֻּלָּן d79bd6bbd6bcd79cd6b8d6bcd79f

==

כֻּלָּן not eqal the כֻּלָּן

===

כֻּלָּן not eqal the כֻּלָּן

strcmp

כֻּלָּן is eqal the כֻּלָּן


Now I have found out that strcmp completely removes diacritics and compares only כלן...

Solution might be unicode normalization the string first.

So I got puzzled... :-(

Not the answer you're looking for? Browse other questions tagged or ask your own question.