Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Why do we need string comparison function?

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

like image 800
Zacky112 Avatar asked Jul 15 '10 11:07

Zacky112


2 Answers

Because there are several variations:

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

  • Is it case sensitive? (strcmp vs strcasecmp, strnatcmp vs strnatcasecmp)
  • Depends it depend on the locale? (strcoll does)
  • Can I specify a collation? (strcoll is affected by setlocale)

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

like image 178
Artefacto Avatar answered Oct 19 '22 14:10

Artefacto


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.

like image 27
ralf.w. Avatar answered Oct 19 '22 14:10

ralf.w.