Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does PHP compare strings with comparison operators?

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.

like image 956
Shakti Singh Avatar asked Oct 15 '12 02:10

Shakti Singh


People also ask

Can you use comparison operators with strings?

The comparison operators also work on strings. To see if two strings are equal you simply write a boolean expression using the equality operator.

Can you use == to compare strings in PHP?

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.

How can we compare two strings in PHP?

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().

What is difference == and === in PHP?

== 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.


2 Answers

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'.

like image 183
coderabbi Avatar answered Sep 19 '22 13:09

coderabbi


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.

like image 43
Brendan Avatar answered Sep 19 '22 13:09

Brendan