I’m comparing strings with comparison operators.
I needs some short of explanations for the below two comparisons and their result.
if('ai' > 'i') { echo 'Yes'; } else { echo 'No'; } output: No
Why do these output this way?
if('ia' > 'i') { echo 'Yes'; } else { echo 'No'; } Output: Yes
Again, why?
Maybe I forgot some basics, but I really need some explanation of these comparison examples to understand this output.
Advertisement
Answer
PHP will compare alpha strings using the greater than and less than comparison operators based upon alphabetical order.
In the first example,
ai
comes beforei
in alphabetical order so the test of>
(greater than) isfalse
– earlier in the order is considered ‘less than’ rather than ‘greater than’.In the second example,
ia
comes afteri
alphabetical order so the test of>
(greater than) istrue
– later in the order being considered ‘greater than’.