How does PHP compare strings with comparison operators?

前端 未结 4 1676
清歌不尽
清歌不尽 2020-12-02 00:14

I\'m comparing strings with comparison operators.

I needs some short of explanations for the below two comparisons and their result.

if(\'ai\' >          


        
相关标签:
4条回答
  • 2020-12-02 00:23

    PHP will compare alpha strings using the greater than and less than comparison operators based upon alphabetical order.

    • In the first example, ai comes before i in alphabetical order so the test of > (greater than) is false - earlier in the order is considered 'less than' rather than 'greater than'.

    • In the second example, ia comes after i alphabetical order so the test of > (greater than) is true - later in the order being considered 'greater than'.

    0 讨论(0)
  • 2020-12-02 00:27

    When both Strings are in Number format, PHP will convert the strings to numbers and convert the values.

    If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically. These rules also apply to the switch statement. The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

    Reference https://www.php.net/manual/en/language.operators.comparison.php

    Edit: formatting.

    0 讨论(0)
  • 2020-12-02 00:31

    To expand on @coderabbi's answer:

    It is the same type of logic as when you order by number in some applications and get results like the following:

    • 0
    • 1
    • 105
    • 11
    • 2
    • 21
    • 3
    • 333
    • 34

    It's not based on string length, but rather each character in order of the string.

    0 讨论(0)
  • 2020-12-02 00:38

    The < and > comparison operator in php will compare the first character of your string, then compare other characters that follows in the strings. Therefore, your first expression ai (first string) and i(second string) a is first character in the string compared with i as first character in the second string with > will return false, and subsequently the second statement will return true due to the same reason. However, if you really need to compare two longer string values with many characters, you may try using substr_compare method:

    substr_compare("abcde", "bc", 1, 2);
    

    in this sample, you have your two strings to be compared, 1 is the offset start position, and 2 represents how many characters you want to compare to the right of those strings. -1 will means the offset start from the end of the first string. e.g. do something like this:

    substr_compare("string1", "string2", 0, length);
    

    also, consider using strcmp() also i.e. strcmp("string1", "string2", length) where length is number of character you want to compare from the two strings.

    0 讨论(0)
提交回复
热议问题