9

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

1
  • 2
    I 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. Commented Jul 15, 2010 at 11:38

2 Answers 2

13

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

Sign up to request clarification or add additional context in comments.

4 Comments

Is there a difference to === though?
If both operands are strings, and in the specific case of strcmp, I don't think there's a difference, no.
@Peka Yeah, they both rely on memcmp. There's just the difference one returns true/false, the other any integer.
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.
3

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

It doesn't return only -1, 1 and 0.
And unless you implement some kind of lookup table you'll end up with a worst-case two comparisons as well.
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 >=.
@J.R.: I think artefacto's answer is quite satisfacting. My answer was only for the WHY!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.