-1

Some examples of PHP functions that contain this description are strcmp () and strcasecmp (), how do they work internally? How does this binary comparison work? I have not been able to understand why these functions return -1, 0 and 1 (or <0, 0 and >0)

Thanks in advance

SRG
  • 53
  • 8
  • Is the question what "binary safe" mean or is it why does the comparison return -1 ,0 and 1 ? – apokryfos Nov 05 '20 at 17:45
  • @apokryfos I mean "binary safe string comparison", and I think this operation results in that -1, 0 and 1 (or <0, 0 and >0) but I can't figure out how it works. – SRG Nov 05 '20 at 17:53
  • 1
    Binary safe is not related with the -1 ,0 and 1 values of the comparison result. You can have a binary safe operation that is not a comparison and you can have a comparison which is not binary-safe but still returns -1, 0 and 1. – apokryfos Nov 05 '20 at 18:05
  • I understand that a binary safe string comparison operation is not necessarily related to -1, 0 and -1 (or else <0, 0 and> 0 according to the PHP documentation of these functions) but what I am dealing with to understand is how these functions work internally. – SRG Nov 05 '20 at 18:14
  • Is the answer below from the docs not sufficient to explain that? – Wesley Smith Nov 05 '20 at 18:14
  • Does this answer your question? [In PHP what does it mean by a function being binary-safe?](https://stackoverflow.com/questions/3264514/in-php-what-does-it-mean-by-a-function-being-binary-safe) – David Brossard Nov 05 '20 at 18:29

1 Answers1

3
  1. If the two strings have identical BEGINNING parts, they are truncated from both strings.
  2. The resulting strings are compared with two possible outcomes:
  • if one of the resulting strings is an empty string, then the length of the non-empty string is returned (the sign depending on the order in which you pass the arguments to the function)
  • in any other case just the numerical values of the FIRST characters are compared. The result is +1 or -1 no matter how big is the difference between the numerical values.

source

François B.
  • 1,096
  • 7
  • 19
  • It took me a little to understand how it works, I see that the key is the first character. Thanks for sharing the link, it helped me a lot. Regards – SRG Nov 05 '20 at 18:40
  • This example also helps a lot: https://www.php.net/manual/en/function.strcmp.php#110975 – SRG Nov 05 '20 at 18:42