The comparision operators < <= > >= can be applied for strings as well. So why do we need special function for string comparision: strcmp ?
-
2I would have guessed that you may supply an own comparator or locale to that function ... but no, it's just the plain old C library function, albeit binary-safe. So maybe to ease porting C code to PHP ... since that apparently happens all the time.Joey– Joey2010-07-15 11:38:38 +00:00Commented Jul 15, 2010 at 11:38
2 Answers
Because there are several variations:
Depending on the function, the answer to these questions vary:
- Is it case sensitive? (
strcmpvsstrcasecmp,strnatcmpvsstrnatcasecmp) - Depends it depend on the locale? (
strcolldoes) - Can I specify a collation? (
strcollis affected bysetlocale)
Additionaly, the comparison operators also give true or false. strcmp gives an integer so it can encode simultaneously whether there's identity (return 0) or, if it not, which is is bigger (depending on whether the value is positive or negative).
4 Comments
=== though?strcmp, I don't think there's a difference, no.<= just fine, that's no inherent advantage to strcmp.Although there are no overloads in PHP for strcmp, strcmp results in 3 different values
-1 for less than, 0 for equals and +1 for greater than the compared string. With < = <= > >= you will have (sometimes) to do multiple checks one after another.
4 Comments
strcmp is used in pretty much the same way, except that you take the comparison operator and apply it to 0. So $a < $b becomes strcmp($a, $b) < 0 – same goes for ==, <=, > and >=.