The comparision operators < <= > >= can be applied for strings as well. So why do we need special function for string comparision: strcmp ?
views:
114answers:
2
+10
A:
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).
Artefacto
2010-07-15 11:37:54
Is there a difference to `===` though?
Pekka
2010-07-15 11:40:07
If both operands are strings, and in the specific case of `strcmp`, I don't think there's a difference, no.
Artefacto
2010-07-15 11:43:12
@Peka Yeah, they both rely on memcmp. There's just the difference one returns true/false, the other any integer.
Artefacto
2010-07-15 12:12:43
@Johannes You're right, I removed that last part.
Artefacto
2010-07-15 12:18:45
For checking whether a string is either »smaller« or equal to another you should be able to use `<=` just fine, that's no inherent advantage to `strcmp`.
Joey
2010-07-15 12:22:19
+3
A:
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.
ralf.w.
2010-07-15 11:45:24
And unless you implement some kind of lookup table you'll end up with a worst-case two comparisons as well.
Artefacto
2010-07-15 11:58:44
Erm, `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 `>=`.
Joey
2010-07-15 12:14:50
@J.R.: I think artefacto's answer is quite satisfacting. My answer was only for the WHY!
ralf.w.
2010-07-15 12:18:25