I'm comparing strings with comparison operators.
I need some sort of explanation 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.
The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.
The most common way you will see of comparing two strings is simply by using the == operator if the two strings are equal to each other then it returns true. This code will return that the strings match, but what if the strings were not in the same case it will not match.
The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().
== Operator: This operator is used to check the given values are equal or not. If yes, it returns true, otherwise it returns false. Syntax: operand1 == operand2. === Operator: This operator is used to check the given values and its data type are equal or not. If yes, then it returns true, otherwise it returns false.
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'.
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:
It's not based on string length, but rather each character in order of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With