How does PHP compare strings with comparison operators?

I am comparing strings with comparison operators.

I need a brief explanation for the two comparisons below and their results.

if('ai' > 'i') { echo 'Yes'; } else { echo 'No'; } output: No 

Why do they output in this way?

 if('ia' > 'i') { echo 'Yes'; } else { echo 'No'; } Output: Yes 

Why again?

Maybe I forgot some basics, but I really need some explanation of these comparative examples to understand this conclusion.

+12
source share
3 answers

PHP will compare alpha strings using larger and smaller operators than comparison, depending on the alphabetical order.

In the first example, ai comes to i in alphabetical order, so checking> (more) is false - earlier in the order it is considered "less" and not "more".

In the second example, ia appears after the i alphabetical order, so the check> (more) is true - later in the order, which is considered to be "more".

+13
source

To extend the answer to @coderabbi:

This is the same type of logic as when ordering by number in some applications and receiving results, such as:

  • 0
  • one
  • 105
  • eleven
  • 2
  • 21
  • 3
  • 333
  • 34

It does not depend on the length of the string, but rather on each character in the order of the string.

+5
source

and> the comparison operator in php will compare the first character of your string, and then compare the other characters that follow in the strings. Thus, your first expression ai (first line) and I (second line) a is the first character in the line compared to i as the first character in the second line s> will return false, and then the second statement will return true because the same reason. However, if you really need to compare two longer string values ​​with many characters, you can try using the substr_compare method:

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

in this example, you need to compare two lines, 1 is the start position of the offset, and 2 is the number of characters you want to compare to the right of these lines. -1 means the beginning of the offset from the end of the first line. for example do something like this:

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

also consider using strcmp () as well, for example strcmp ("string1", "string2", length), where length is the number of characters you want to compare with two strings.

0
source

All Articles