Search code examples
phpstringstring-comparison

In PHP what does it mean by a binary safe string comparison?


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


Solution

    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