tags:

views:

114

answers:

2

The comparision operators < <= > >= can be applied for strings as well. So why do we need special function for string comparision: strcmp ?

+10  A: 

Because there are several variations:

Depending on the function, the answer to these questions vary:

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
Is there a difference to `===` though?
Pekka
If both operands are strings, and in the specific case of `strcmp`, I don't think there's a difference, no.
Artefacto
@Peka Yeah, they both rely on memcmp. There's just the difference one returns true/false, the other any integer.
Artefacto
@Johannes You're right, I removed that last part.
Artefacto
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
+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.
It doesn't return only -1, 1 and 0.
Artefacto
And unless you implement some kind of lookup table you'll end up with a worst-case two comparisons as well.
Artefacto
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
@J.R.: I think artefacto's answer is quite satisfacting. My answer was only for the WHY!
ralf.w.