strcmp – String Compare

Here are some of string comparation php functions:

  • strcmp($s1, $s2) – returns 0 if $s1 and $s2 are equal, a negativ value (-1) if $s1<$s2 and positive value (1) if $s1>$s2. The string comparation is case-sensitive, character by character, comparing character’s codes. Uppercase chars are considered smaller than minuscule chars. Numbers are considered smaller than letters.
  • strcasecmp($s1, $s2) – idem, but the string compare is case-insensitive
  • strncmp($s1, $s2, $nr) – like strcmp() but it compare only the first $nr chars of the 2 strings.
  • strncasecmp($s1, $s2, $nr) – idem, case-insensitive
  • strnatcmp($s1, $s2) – natural comparation, case-sensitive of the 2 strings (like natsort())
  • strnatcasecmp($s1, $s2) – idem, but case-insensitive


String compare function examples

  1. <?php
  2. $s1 = "1 Euro";
  3. $s2 = "2 Euro";
  4. $s3 = "10 Euro";
  5. $s4 = "10 euro";
  6. echo strcmp($s1, $s2); // -1 ($s1 is alphabetically before $s2)
  7. echo strcmp($s3, $s4); // -1 (the code of E char is before e char)
  8. echo strcasecmp($s3, $s4); // 0 (case insensitive, the two strings are equal)
  9. echo strcmp($s2, $s3); // 1 (char 1 is before 2)
  10. echo strnatcmp($s2, $s3); // -1 (char 2 as number is before 10)
  11. echo strncmp($s1, $s4, 1); // 0 (comparing only the first char, there is equality)
  12. ?>

No related php tutorials.

bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark
tabs-top

Leave a Reply