Comparing strings

int strcmp ( string str1, string str2)

int strcasecmp ( string str1, string str2)

Strcmp(), and its case-insensitive sibling strcasecmp(), is a quick way of comparing two words and telling whether they are equal, or whether one comes before the other. It takes two words for its two parameters, and returns -1 if word one comes alphabetically before word two, 1 if word one comes alphabetically after word two, or 0 if word one and word two are the same.

<?php
    $string1 = "foo";
    $string2 = "bar";
    $result = strcmp($string1, $string2);

    switch ($result) {
        case -1: print "Foo comes before bar"; break;
        case 0: print "Foo and bar are the same"; break;
        case 1: print "Foo comes after bar"; break;
    }
?>

It is not necessary for us to see that "foo" comes after "bar" in the alphabet because we already know it does, however you would not bother running strcmp() if you already knew the contents of the strings - it is most useful when you get unknown input and you want to sort it.

As you can see, strcmp() can serve in place of == because it returns 0 when two strings are equal. There is an urban myth amongst PHP programmers that == is faster than strcmp(), however the reality is that it is just as fast, and you can use the two interchangeably if you wish. One thing, though: using ==, you get a "1" if two strings match, whereas with strcmp() you get a 0, so be careful!

 

Want to learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Padding out a string >>

Previous chapter: Removing HTML from a string

Jump to:

 

Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.